我有一个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: 试图在DataFrame的切片副本上设置一个值,但在查看doc后仍然无法理解该值。
谢谢!
答案 0 :(得分:0)
我终于用DataFrame.rename()函数解决了它