无法更改熊猫数据中的列名

时间:2019-03-13 19:57:49

标签: python pandas dataframe

我有一个看起来像这样的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数据框中并尝试打印时,它看起来如下:

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'})

但仍然显示旧名称

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

您可以提供字典来替换列并为您提供1:1映射。添加就位标记将在现有数据框中执行此操作,而忽略它会为您提供一个具有新列名的新数据框。

df.rename(columns = {
    'property_1': 'P1',
    'property_2': 'P2',
    'property_3': 'P3',
    'property_4': 'P4',
    'missing': 'Missing'
    }, inplace = True)
相关问题