根据堆叠条件为具有层次索引的 pandas DataFrame 赋值

Assign value to pandas DataFrame with hierarchical index based on stacked condition

我有一个 pandas DataFrame,它有一个两级层次索引。我想根据条件从某个子集设置一个值到另一个子集。

我认为最好用一个小例子来解释:

import numpy as np
import pandas as pd

example = pd.DataFrame({'ind_1': 5*[0] + 5*[1], 'ind_2': np.concatenate([np.arange(5), np.arange(5)]),
                        'col_1': np.random.random(size=10), 'col_2': np.random.random(size=10)})
example = example.set_index(['ind_1', 'ind_2'])
example_0 = example.loc[0]
example_1 = example.loc[1]
example['condition'] = False

condition = example_1['col_1'] > 0.5

使用数据帧

$ example
                col_1     col_2  condition
ind_1 ind_2                               
0     0      0.430966  0.064335      False
      1      0.631710  0.313696      False
      2      0.354766  0.479626      False
      3      0.548612  0.793249      False
      4      0.144033  0.352583      False
1     0      0.586365  0.578001      False
      1      0.306403  0.399591      False
      2      0.312621  0.439042      False
      3      0.010637  0.232054      False
      4      0.762034  0.293433      False

$ example_0
          col_1     col_2
ind_2                    
0      0.430966  0.064335
1      0.631710  0.313696
2      0.354766  0.479626
3      0.548612  0.793249
4      0.144033  0.352583

$ example_1
          col_1     col_2
ind_2                    
0      0.586365  0.578001
1      0.306403  0.399591
2      0.312621  0.439042
3      0.010637  0.232054
4      0.762034  0.293433

$ condition
ind_2
0     True
1    False
2    False
3    False
4     True

现在我想赋值如下

example.loc[0].loc[condition] = True

结果(理所当然)SettingWithCopyWarning 并且在更复杂的情况下根本不起作用。

预期输出为

$ example
                col_1     col_2  condition
ind_1 ind_2                               
0     0      0.430966  0.064335      True
      1      0.631710  0.313696      False
      2      0.354766  0.479626      False
      3      0.548612  0.793249      False
      4      0.144033  0.352583      True
1     0      0.586365  0.578001      False
      1      0.306403  0.399591      False
      2      0.312621  0.439042      False
      3      0.010637  0.232054      False
      4      0.762034  0.293433      False

所以对于 ind_1 == 0 我们设置条件。但请注意,条件是针对 ind_1 == 1

计算的

这样做最干净的方法是什么?

您可以 reindex on condition 然后传递 numpy 数组:

example.loc[0, 'condition'] = condition.reindex(example.loc[0].index).values

注意 你不分配链索引,即 .loc[].loc[],但做一个 .loc[ind, column].

输出:

                col_1     col_2  condition
ind_1 ind_2                               
0     0      0.295983  0.241758      False
      1      0.707799  0.765772       True
      2      0.822369  0.062530       True
      3      0.816543  0.621883      False
      4      0.048521  0.738549       True
1     0      0.433304  0.527344      False
      1      0.727886  0.557176      False
      2      0.653163  0.686719      False
      3      0.020094  0.887114      False
      4      0.777072  0.506128      False