gpt4 book ai didi

Pandas 截断列名

转载 作者:行者123 更新时间:2023-12-05 02:03:41 26 4
gpt4 key购买 nike

我想截断列标题(仅在打印时),我正确地处理了内容而不是标题。我正在使用:

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

谢谢

最佳答案

请注意,pd.set_option('display.max_colwidth', 18) 只会修剪数据中的内容,不会修剪列标题。我认为这是 Pandas 没有提供的错误或选项。所以你必须手动执行此操作。不幸的是,解决方案不是很干净。您可以决定创建一个函数,这样您就可以在每次要打印数据帧时调用该函数。

如果我理解正确,您想要修剪数据框列的标题。这里有一个选项供您尝试。

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]

关于Pandas 截断列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64976267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com