考虑pd.Series
s
s = pd.Series(np.arange(6),
pd.MultiIndex.from_product([[1, 2], [1, 2, 3]]))
1 1 0
2 1
3 2
2 1 3
2 4
3 5
dtype: int64
我想用 4
替换索引中 3
的所有值。
我刚刚想出这个,但我不喜欢它。
lvl0 = s.index.get_level_values(0)
lvl1 = s.index.get_level_values(1)
s.index = pd.MultiIndex.from_tuples(zip(lvl0, np.where(lvl1 == 3, 4, lvl1)))
s
1 1 0
2 1
4 2
2 1 3
2 4
4 5
dtype: int64
最佳答案
您可以使用s.index.levels = [[1, 2], [1, 2, 4]]
,但您可能会收到 FutureWarning:
FutureWarning: setting `levels` directly is deprecated. Use set_levels instead
所以你可以尝试一下
>>> s.index = s.index.set_levels([[1, 2], [1, 2, 4]])
>>> s
1 1 0
2 1
4 2
2 1 3
2 4
4 5
关于python - 如何替换多索引第 n 级中等于 x 的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693359/