如何在多级数据帧上正确使用.loc?

时间:2016-12-05 21:23:42

标签: python pandas indexing dataframe

鉴于df'AB':

xyz

我想根据列['B','C']的条件向级别'B'添加一个'new'列。我想专门使用df.loc,像这样:

A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
         columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])
B = pd.DataFrame([[3, 3, 3], [2, 2, 2], [4, 4, 4], [5, 5, 5], [6, 6, 6]],
         columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])

A.columns = pd.MultiIndex.from_product([['A'], A.columns])
B.columns = pd.MultiIndex.from_product([['B'], B.columns])
AB = pd.concat([A, B], axis = 1)

问题是这个程序创建了一个'new'df而不是填充列['B','new']。

所需的输出是:

AB['B', 'new'] = 0
AB.loc[AB['B', 'C'] >= 3, 'new'] = 1

1 个答案:

答案 0 :(得分:1)

使用元组引用多级索引/列:

AB[('B', 'new')] = 0
AB.loc[AB[('B', 'C')] >= 3, ('B', 'new')] = 1

或者,在一行中:

AB[('B', 'new')] = AB[('B', 'C')].ge(3).astype(int)

结果输出:

   A        B          
   A  B  C  A  B  C new
1  1  5  2  3  3  3   1
2  2  4  4  2  2  2   0
3  3  3  1  4  4  4   1
4  4  2  2  5  5  5   1
5  5  1  4  6  6  6   1
相关问题