gpt4 book ai didi

python - Pandas 替换多索引行中的值

转载 作者:行者123 更新时间:2023-12-03 02:58:21 25 4
gpt4 key购买 nike

所以,我有一个 MultiIndex DataFrame,但我无法找出行来修改行索引值。

在此示例中,我想设置 c = 1,其中“a”索引为 4:

import pandas as pd
import numpy as np

df = pd.DataFrame({('colA', 'x1'): {(1, np.nan, 0): np.nan, (4, np.nan, 0): np.nan},
('colA', 'x2'): {(1, np.nan, 0): np.nan, (4, np.nan, 0): np.nan},
('colA', 'x3'): {(1, np.nan, 0): np.nan, (4, np.nan, 0): np.nan},
('colA', 'x4'): {(1, np.nan, 0): np.nan, (4, np.nan, 0): np.nan}})

df.index.set_names(['a', 'b', 'c'], inplace=True)

print(df)


colA
x1 x2 x3 x4
a b c
1 NaN 0 NaN NaN NaN NaN
4 NaN 0 NaN NaN NaN NaN

期望的输出:

            colA
x1 x2 x3 x4
a b c
1 NaN 0 NaN NaN NaN NaN
4 NaN 1 NaN NaN NaN NaN

感谢任何帮助。

最佳答案

假设我们从 df 开始。

x = df.reset_index()
x.loc[x[x.a == 4].index, 'c'] = 1
x = x.set_index(['a', 'b', 'c'])
print(x)

colA
x1 x2 x3 x4
a b c
1 NaN 0 NaN NaN NaN NaN
4 NaN 1 NaN NaN NaN NaN

关于python - Pandas 替换多索引行中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61806546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com