Pandas截断列名

3

我希望在打印时截断列标题,内容处理正确但标题没有,我正在使用:

pd.set_option('display.max_colwidth', 18)

谢谢


什么是问题?你是在问你所拥有的命令是否正确吗? - Joe Ferndz
pd.set_option('max_colwidth',n),其中n为列名的长度。这将设置每个列的长度,以便在显示时使用。display.max_colwidth设置列的最大宽度。此长度或更长的单元格将使用省略号截断。有关详细信息,请参见https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#frequently-used-options。 - Joe Ferndz
更新的问题,我说的是列标题而不是内容。 - Fernando V
这是否意味着列中的实际值可以超出最大列宽?例如:如果第1行中一个值的长度为30,但列标题宽度限制为18,则应使用最多18个字符打印列标题和完整的30个字符的第1行数据吗? - Joe Ferndz
这个回答解决了你的问题吗?https://dev59.com/01oV5IYBdhLWcg3wPs0Y - mosc9575
1个回答

4
请注意,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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接