How to set the pandas dataframe data left/right alignment?
I use pd.set_option("display.colheader_justify","right")
to set the column header. But I can't find the option for data by pd.describe_option()
.
How to set the data within a dataframe display left or right alignment for each column? Or, is it possible to define a format template for the whole row data display?
Solution 1:
If you want to change the display in a Jupyter Notebook, you can use the Style feature.
# Test data
df = DataFrame({'text': ['foo', 'bar'],
'number': [1, 2]})
df.style.set_properties(**{'text-align': 'right'})
Solution 2:
The answer given by @Romain is great but I would like to summarize some comments:
# Test data
df = DataFrame({'text': ['foo', 'bar'],'number': [1, 2]})
dfStyler = df.style.set_properties(**{'text-align': 'left'})
dfStyler.set_table_styles([dict(selector='th', props=[('text-align', 'left')])])
will align all table text and the column headers as well.
Solution 3:
pip3 install tabulate
from tabulate import tabulate
df = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print(tabulate(df, showindex=False, headers=df.columns))
Text Value
------ -------
abcdef 12.34
x 4.2
This will automatically align pandas header and column data to good view format. Automatically align pandas dataframes columns data to left. Removes showing of the index in pandas dataframe. Puts ---- between the header and column data.