[英]How to rename a pandas DataFrame index label based on other column value
我有一個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的切片副本上設置一個值,在查看文檔后仍然無法理解該值。
謝謝!
我終於用DataFrame.rename()函數解決了它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.