Reputation: 285
I want to truncate the column headers (only when printing), I am doing properly with the content but not headers. I am using:
pd.set_option('display.max_colwidth', 18)
Thanks
Upvotes: 5
Views: 4019
Reputation: 8508
Please note that pd.set_option('display.max_colwidth', 18)
will only trim the contents in the data and not the column header. I think this is a bug or an option that Pandas does not provide. So you have to do this manually. Unfortunately, the solution is not very clean. You can decide to create a function so you can just call that function every time you want to print the dataframe.
If I understand correctly, you want to trim the header of the dataframe columns. Here's an option for you to try.
import pandas as pd
c = ['This_Is_A_Long_Name_For_Column_1','This_Is_A_Long_Name_For_Column_2',
'This_Is_A_Long_Name_For_Column_3','This_Is_A_Long_Name_For_Column_4']
d = [['This is data in row 1 and column 1','This is data in row 1 and column 2',
'This is data in row 1 and column 3','This is data in row 1 and column 4'],
['This is data in row 2 and column 1','This is data in row 2 and column 2',
'This is data in row 2 and column 3','This is data in row 2 and column 4'],
['This is data in row 3 and column 1','This is data in row 3 and column 2',
'This is data in row 3 and column 3','This is data in row 3 and column 4'],
['This is data in row 3 and column 1','This is data in row 4 and column 2',
'This is data in row 3 and column 3','This is data in row 4 and column 4']]
df = pd.DataFrame(d,columns=c)
temp_col_name = df.columns.to_list()
df.rename(columns=lambda x: x[:18], inplace=True) #this will truncate the column name. Then print the dataframe
print (df)
df.columns = temp_col_name #once you are done printing, rename column name back to original
print (df)
The output of this will be:
This_Is_A_Long_Nam ... This_Is_A_Long_Nam
0 This is data in row 1 and column 1 ... This is data in row 1 and column 4
1 This is data in row 2 and column 1 ... This is data in row 2 and column 4
2 This is data in row 3 and column 1 ... This is data in row 3 and column 4
3 This is data in row 3 and column 1 ... This is data in row 4 and column 4
[4 rows x 4 columns]
This_Is_A_Long_Name_For_Column_1 ... This_Is_A_Long_Name_For_Column_4
0 This is data in row 1 and column 1 ... This is data in row 1 and column 4
1 This is data in row 2 and column 1 ... This is data in row 2 and column 4
2 This is data in row 3 and column 1 ... This is data in row 3 and column 4
3 This is data in row 3 and column 1 ... This is data in row 4 and column 4
[4 rows x 4 columns]
Upvotes: 4