首页 > 解决方案 > 如何根据其他列值重命名熊猫 DataFrame 索引标签

问题描述

我有一个 df,我正在尝试根据同一行上列的值更新 multiIndex 中某些标签的值。

目前,我删除了索引级别并使用了一些掩码,就好像它是一个值列一样,但我觉得必须有一种更清洁的方法来做到这一点

iterables = [['bar', 'baz', 'foo', 'qux'], ['A', 'B']]
index = pd.MultiIndex.from_product(iterables, names=['loadcase', 'location'])
df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=['fx','fy','fz'])
df

                        fx       fy       fz
loadcase location                           
bar      A        -3.8e-01  2.3e-01 -2.3e+00
         B        -1.4e+00 -7.4e-01  2.6e-01
baz      A         1.1e+00 -1.1e+00 -1.2e-01
         B         5.6e-01  3.7e-01  2.8e+00
foo      A         6.2e-02 -6.2e-02 -9.7e-01
         B        -5.7e-01 -6.4e-01 -1.1e+00
qux      A         2.5e+00 -1.0e-01  4.1e-02
         B        -9.2e-01  9.8e-02 -1.0e+00

# drop the index location so it can be easily searched for.    
df.reset_index(level="location", inplace=True)

mask = (df["location"] == 'A') & (df["fx"] < 0)
df["location"].loc[mask] = "{}_NEG".format('A')

mask2 = df["location"] == 'A'
df["location"].loc[mask2] = "{}_POS".format('A')

#returning the index like it is the standard
df.reset_index(inplace=True)
df.set_index(["loadcase","location"], inplace=True)

这给了我预期的结果:

                        fx       fy       fz
loadcase location                           
bar      A_NEG    -3.8e-01  2.3e-01 -2.3e+00
         B        -1.4e+00 -7.4e-01  2.6e-01
baz      A_POS     1.1e+00 -1.1e+00 -1.2e-01
         B         5.6e-01  3.7e-01  2.8e+00
foo      A_POS     6.2e-02 -6.2e-02 -9.7e-01
         B        -5.7e-01 -6.4e-01 -1.1e+00
qux      A_POS     2.5e+00 -1.0e-01  4.1e-02
         B        -9.2e-01  9.8e-02 -1.0e+00

但这很丑陋,我不希望将索引放到常规列中。如何屏蔽数据框并同时访问标签(或特定列)以更改值?

此外,我收到错误 SettingWithCopyWarning: A value is trying to be set on a slice of a DataFrame,在查看文档后仍然无法理解它。

谢谢!

标签: pythonpandas

解决方案


我终于用 DataFrame.rename() 函数解决了这个问题


推荐阅读