gpt4 book ai didi

python - 无法更改 Pandas 数据中的列名

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:30 25 4
gpt4 key购买 nike

我有一个看起来像这样的 python 字典:

d = {'comp_1': {'property_4': 24, 'property_2': 45, 'property_3': 124, 'missing': 39, 'property_1': 16}, 
'comp_2': {'property_4': 23, 'property_2': 49, 'property_3': 126, 'property_1': 16, 'missing': 38},
'comp_3': {'property_4': 24, 'property_2': 43, 'property_1': 19, 'missing': 30, 'property_3': 116}}

当我将它加载到 panda dataframe 并尝试打印它时,它看起来如下:

df = pd.DataFrame.from_dict(hits, orient='index')
print(df)

输出:

        missing  property_1  property_2  property_3  property_4
comp_1 39 16 45 124 24
comp_2 38 16 49 126 23
comp_3 30 19 43 116 24

现在,我想重命名列,所以我尝试:

df = pd.DataFrame.from_dict(hits, orient='index' columns=reversed(['Missing', 'P1', 'P2', 'P3', 'P4']))

这会产生空数据框(我假设这是因为字典中不存在这些键?):

Empty DataFrame
Columns: []
Index: []

如果我尝试这样做:

df = pd.DataFrame.from_dict(hits, orient='index')
columns = reversed(['Missing', 'P1', 'P2', 'P3', 'P4'])
df.columns=columns

列按顺序重命名不会保留,所以每次我运行代码时,数字都与列不对应,例如:

        P4  P3   P2  P1  Missing
comp_1 16 24 124 45 39
comp_2 16 23 126 49 38
comp_3 19 24 116 43 30

和:

        P4  P3  P2   P1  Missing
comp_1 24 16 39 124 45
comp_2 23 16 38 126 49
comp_3 24 19 30 116 43

我猜我需要在将数据加载到数据帧时以某种方式提供嵌套字典中的键,但我不确定该怎么做。还是我需要做其他事情?

编辑:我还尝试使用字典重命名列,如下所示:

df.rename({'missing': 'Missing', 'property_1': 'P1', 'property_2': 'P2', 'property_3': 'P3',
'property_4': 'P4'})

但仍然显示旧名称

最佳答案

不幸的是,to_dict 中的columns 参数仅指定了您要选择的列。例如,

pd.DataFrame.from_dict(hits, orient='index', columns=['property_4'])

property_4
comp_1 24
comp_2 23
comp_3 24

仅选择“property_4”列,忽略其他所有内容。当然,这是有道理的,因为字典天生就没有顺序。您唯一的选择是使用 DataFrame.rename() 重命名键或重命名列。

cmap = {'property_1': 'P1', 'property_2': 'P2', 'property_3': 'P3', 
'property_4': 'P4', 'missing': 'Missing'}
df = df.rename(columns=cmap)
df

P4 P2 P3 Missing P1
comp_1 24 45 124 39 16
comp_2 23 49 126 38 16
comp_3 24 43 116 30 19

关于python - 无法更改 Pandas 数据中的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150254/

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