Issue
I am trying to format the output in an IPython notebook. I tried using the to_string function, and this neatly lets me eliminate the index column. But the textual data is right justified.
In [10]:
import pandas as pd
columns = ['Text', 'Value']
a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print (a.to_string (index=False))
Text Value
abcdef 12.34
x 4.20
The same is true when just printing the dataframe.
In [12]:
print (a)
Text Value
0 abcdef 12.34
1 x 4.20
The justify argument in the to_string function, surprisingly, only justifies the column heading.
In [13]:
import pandas as pd
columns = ['Text', 'Value']
a = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print (a.to_string (justify='left', index=False))
Text Value
abcdef 12.34
x 4.20
How can I control the justification settings for individual columns?
Solution
If you're willing to use another library, tabulate will do this -
$ pip install tabulate
and then
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
It has various other output formats also.
Answered By - Brian Burns
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.