打印数据框,列中心对齐

时间:2012-10-20 03:47:00

标签: r printing dataframe formatting center-align

我想打印一列中心对齐的数据框。下面是我尝试的内容,我认为打印数据框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

2 个答案:

答案 0 :(得分:8)

问题在于,为了使其按预期工作,还需要指定“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

答案 1 :(得分:0)

调用此函数以获取要显示的数据框:

def pd_centered(df):
    return df.style.set_table_styles([
        {"selector": "th", "props": [("text-align", "center")]},
        {"selector": "td", "props": [("text-align", "center")]}])

例如:

display(pd_centered(original_df))

这将使标头和实际数据单元格居中对齐,并且您可以根据需要删除tdth以禁用其中任何一个。

来源:https://github.com/pandas-dev/pandas/issues/12144