我有一个列上带有多索引的数据框:
df = pd.DataFrame({('a', 'status'): [0.1, 0.2, 0.3],
('a', 'value'): [1.1, 1.2, 1.3],
('b', 'status'): [0.1, 0.2, 0.3],
('b', 'value'): [2.1, 2.2, 2.3],
('c', 'status'): [0.1, 0.2, 0.3]})
我的目标是将所有
value
列乘以一个标量,或者向它们添加一个标量。我一直在努力寻找与直接索引或 iloc
一起使用的适当表达式,但似乎找不到合适的表达式。以下是一些失败的尝试:
>>> df[(None, 'value')] += 2
...
KeyError: 2
>>> df.iloc[:, (None, 'value')] += 2
...
IndexingError: Too many indexers
我认为制作列的掩码或索引是可能的,尽管不是很优雅,所以我尝试了:
>>> df.columns.levels[1] == 'value'
array([False, True])
这对我拥有的五个实际列没有帮助。
您需要切片机:
df.loc[:, (slice(None), "value")] +=2
#another variant
# df.loc[:, pd.IndexSlice[:, "value"]] += 2
输出:
print(df)
a b c
status value status value status
0 0.1 3.1 0.1 4.1 0.1
1 0.2 3.2 0.2 4.2 0.2
2 0.3 3.3 0.3 4.3 0.3
使用
df.where()
是一种选择:
m = df.columns.get_level_values(1) == 'value'
df.add(2).where([m]*df.shape[0],df)
或
df.add((df.columns.get_level_values(1) == 'value')*2)
输出:
a b c
status value status value status
0 0.1 3.1 0.1 4.1 0.1
1 0.2 3.2 0.2 4.2 0.2
2 0.3 3.3 0.3 4.3 0.3