我希望在打印时截断列标题,内容处理正确但标题没有,我正在使用:
pd.set_option('display.max_colwidth', 18)
谢谢
我希望在打印时截断列标题,内容处理正确但标题没有,我正在使用:
pd.set_option('display.max_colwidth', 18)
谢谢
pd.set_option('display.max_colwidth', 18)
只会裁剪数据的内容而不是列标题。我认为这是一个 Pandas 没有提供的 bug 或选项。所以你必须手动解决。不幸的是,解决方案并不是非常干净。你可以决定创建一个函数,这样每次打印数据框时都可以直接调用该函数。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)
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]