如果满足两个条件,我希望掩码(或分配“na”)数据帧中列的值。如果按行执行条件,这将相对简单,例如:

mask = ((df['A'] < x) & (df['B'] < y))
df.loc[mask, 'C'] = 'NA'

但我在数据框中不太清楚如何执行此任务,数据框的结构大致如下:
df = pd.DataFrame({ 'A': (188, 750, 1330, 1385, 188, 750, 810, 1330, 1385),
                     'B': (2, 5, 7, 2, 5, 5, 3, 7, 2),
                     'C': ('foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar') })

    A    B C
0   188  2 foo
1   750  5 foo
2   1330 7 foo
3   1385 2 foo
4   188  5 bar
5   750  5 bar
6   810  3 bar
7   1330 7 bar
8   1385 2 bar

'C' == 'foo'时的列“a”中的值也应该在'C' == 'bar'时找到(类似于索引),尽管它可能在“foo”和“bar”中都缺少数据。如果“foo”和“bar”都小于5或其中任何行丢失,我如何屏蔽(或分配“na”)列“b”的行?在上面的示例中,输出如下:
    A    B C
0   188  2  foo
1   750  5  foo
2   1330 7  foo
3   1385 NA foo
4   188  5  bar
5   750  5  bar
6   810  NA bar
7   1330 7  bar
8   1385 NA bar

最佳答案

这里有一个解决方案。其思想是从两个映射序列m1m2构造两个布尔掩码s1s2然后使用pd.Series.mask屏蔽系列B

# create separate mappings for foo and bar
s1 = df.loc[df['C'] == 'foo'].set_index('A')['B']
s2 = df.loc[df['C'] == 'bar'].set_index('A')['B']

# use -np.inf to cover missing mappings
m1 = df['A'].map(s1).fillna(-np.inf).lt(5)
m2 = df['A'].map(s2).fillna(-np.inf).lt(5)

df['B'] = df['B'].mask(m1 & m2)

print(df)

      A    B    C
0   188  2.0  foo
1   750  5.0  foo
2  1330  7.0  foo
3  1385  NaN  foo
4   188  5.0  bar
5   750  5.0  bar
6   810  NaN  bar
7  1330  7.0  bar
8  1385  NaN  bar

09-04 09:31
查看更多