打印数据框时,如何使列居中对齐

10

我想打印一个数据框,其中列居中对齐。以下是我尝试过的内容,我认为打印数据框test1会导致列居中对齐,但事实并非如此。你有什么想法,我该如何做到这一点?

test=data.frame(x=c(1,2,3),y=c(5,6,7))
names(test)=c('Variable 1','Variable 2')
test[,1]=as.character(test[,1])
test[,2]=as.character(test[,2])
test1=format(test,justify='centre')
print(test,row.names=FALSE,quote=FALSE)
 Variable 1 Variable 2
          1          5
          2          6
          3          7
print(test1,row.names=FALSE,quote=FALSE)
 Variable 1 Variable 2
          1          5
          2          6
          3          7

你是指列的中心吗?所以1、2、3排在“变量1”的“a”下面(大致上)? - Tyler Rinker
@TylerRinker 是的,那就是我的意思。 - Glen
@Glen,我的回答是否已经充分解决了你的问题?如果没有,请添加评论以便进一步处理您的问题。 - A5C1D2H2I1M1N2O1R2T1
2个回答

14
问题在于,为了使此代码按照您的期望运行,需要同时指定“width”参数。
以下是一个示例:
test.1 <- data.frame(Variable.1 = as.character(c(1,2,3)), 
                     Variable.2 = as.character(c(5,6,7)))

# Identify the width of the widest column by column name
name.width <- max(sapply(names(test.1), nchar))
format(test.1, width = name.width, justify = "centre")
#   Variable.1 Variable.2
# 1     1          5     
# 2     2          6     
# 3     3          7  

但是,当变量名不同长度时,这种方法如何运作呢?效果并不好。

test.2 <- data.frame(A.Really.Long.Variable.Name = as.character(c(1,2,3)), 
                     Short.Name = as.character(c(5,6,7)))

name.width <- max(sapply(names(test.2), nchar))
format(test.2, width = name.width, justify = "centre")
#   A.Really.Long.Variable.Name                  Short.Name
# 1              1                           5             
# 2              2                           6             
# 3              3                           7             

当然,有一个变通方法:通过使用format()填充空格来使每个变量名称的“宽度”相等。

orig.names <- names(test.2) # in case you want to restore the original names
names(test.2) <- format(names(test.2), width = name.width, justify = "centre")
format(test.2, width = name.width, justify = "centre")
#   A.Really.Long.Variable.Name         Short.Name         
# 1              1                           5             
# 2              2                           6             
# 3              3                           7

我打算使用sprintf +1。 - Tyler Rinker
如果一列中有字符而不是数字,并且它们比列名本身还要长,似乎无法正常工作,有什么替代方案吗? - ForEverNewbie

3
调用此函数以获取类似于该样式的数据框:
def pd_centered(df):
    return df.style.set_table_styles([
        {"selector": "th", "props": [("text-align", "center")]},
        {"selector": "td", "props": [("text-align", "center")]}])

e.g.:

display(pd_centered(original_df))

这将使表头和实际数据单元格都居中对齐,如果需要可以删除tdth中的任意一个来禁用其中之一。
来源:https://github.com/pandas-dev/pandas/issues/12144

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接