python - 如何根据其他列值重命名熊猫 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,在查看文档后仍然无法理解它。
谢谢!
解决方案
我终于用 DataFrame.rename() 函数解决了这个问题
推荐阅读
- javascript - 如何在测试环境之外运行 webdriver-io 并仍然访问全局变量 $ 和 $$?
- php - 无法将下拉字符串值与 yii2 中的 int(用户角色)进行比较
- image-processing - 如何加快 ImageNet 的“ImageFolder”
- git - Gitlab 错误:RPC 失败;HTTP 403 curl 22 The requested URL returned error: 403 Forbidden
- javascript - 为什么我的代码给我,错误:句柄已经在运行?
- apache-spark - 如何使用 Apache Spark ML 库对随机森林执行网格搜索
- coq - 不能统一两个相同的假设
- jquery - 具有数据属性的 Jquery 和 img 库不起作用
- python-3.x - Tensorflow 在 pycharm 上看不到 gpu
- c# - 实体框架和带有任务的 MongoClient