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()
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.
In my situation, I have a class wrapper around my Pandas DataFrame. This allows me to left-justify the DataFrame's string output by customizing the wrapper's __str__()
method.
Here's how I solved the problem for my application, based on Unutbu's answer to a similar question. The Pandas DataFrame is referenced by self.data
:
def __str__(self):
"""
Return the test stats report as a single string
with left-justified columns.
"""
# Columns containing boolean values need different format strings
# to avoid 'ValueError: Invalid format specifier' exceptions.
BOOL_COLUMNS = ['success',]
formatters = {}
for li in list(self.data.columns):
if li in BOOL_COLUMNS:
form = "{{!s:<5}}".format()
else:
max = self.data[li].str.len().max()
form = "{{:<{}s}}".format(max)
formatters[li] = functools.partial(str.format,form)
return self.data.to_string(formatters=formatters, index=False)
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'})
you can control it by a new context:
with pd.option_context('display.colheader_justify','right'):
...
I wrapped @Hagbard's answer in a function to use it whenever I wish to display a pandas dataframe consisting English text on a notebook cell:
from pandas import DataFrame
def left_align(df: DataFrame):
left_aligned_df = df.style.set_properties(**{'text-align': 'left'})
left_aligned_df = left_aligned_df.set_table_styles(
[dict(selector='th', props=[('text-align', 'left')])]
)
return left_aligned_df
To show a dataframe, I simply write this:
left_align(df.head())
Caution: For large datasets, it prints all the rows and columns of df
without any abstraction, so Jupyter crashes! That's why I use it with .head()
or .tail()
or some other limit.)
If you wanna align both text and header to the left for example you can use:
df.style.set_properties(**{'text-align': 'left'}).set_table_styles([ dict(selector='th', props=[('text-align', 'left')] ) ])
This first sets the text to the left and then the header.