I would like to print a data frame where the columns are center aligned. Below is what I have I tried, I thought printing the data frame test1 would result in the columns being aligned in the center but this is not the case. Any thoughts on how I can do this?
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
The problem is that in order for this to work as you expect, the "
width
" argument needs to also be specified.Here's an example:
But, how does this approach work with columns where the variable names are different lengths? Not so well.
There is, of course, a workaround: change the "width" of each variable name to be equal lengths by padding them with spaces (using
format()
)call this function to get a dataframe to display like that:
e.g.:
This will center align both the headers and the actual data cells, and you may remove either the
td
or theth
to disable either one if you like.Source: https://github.com/pandas-dev/pandas/issues/12144