熊猫替换多索引行中的值

问题描述 投票:2回答:2

因此,我有一个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

感谢您的任何帮助。

python pandas multi-index
2个回答
2
投票

解决方案

分离索引,对其进行处理,然后将其与数据放回原处。

逻辑

  1. 分离索引并将其作为数据框处理
  2. 准备多重索引
  3. 以下两个选项之一:
    • 将数据和MultiIndex结合在一起Method-1
    • 更新原始数据帧的索引Method-2

代码

# separate the index and process it
names = ['a', 'b', 'c'] # same as df.index.names
#dfd = pd.DataFrame(df.to_records())
dfd = df.index.to_frame().reset_index(drop=True)
dfd.loc[dfd['a']==4, ['c']] = 1

# prepare index for original dataframe: df
index = pd.MultiIndex.from_tuples([tuple(x) for x in dfd.loc[:, names].values], names=names)

## Method-1
# create new datframe with updated index
dfn = pd.DataFrame(df.values, index=index, columns=df.columns)
# dfn --> new dataframe

## Method-2
# reset the index of original dataframe df
df.set_index(index)

输出

            colA            
              x1  x2  x3  x4
a   b   c                   
1.0 NaN 0.0  NaN NaN NaN NaN
4.0 NaN 1.0  NaN NaN NaN NaN

虚拟数据

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)

3
投票

假设我们从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
© www.soinside.com 2019 - 2024. All rights reserved.