Pandas基于多个其他列的条件逻辑添加新列

4

I have a pandas dataframe like this:

aa bb cc dd ee
a  a  b  b  foo
a  b  a  a  foo
b  a  a  a  bar
b  b  b  b  bar

如果第1到4列的值为a,我想要添加一个新的列。

结果将会是这样的:

aa bb cc dd ee  ff
a  a  b  b  foo a
a  b  a  a  foo a
b  a  a  a  bar a
b  b  b  b  bar b

逻辑如下: 如果第1到4列中的任何一个值为a,则列ffa,否则为b
我可以定义一个函数,并手动处理每一列,例如:
def some_function(row);
   if row['aa']=='a' or row['bb']=='a' or row['cc']=='a' or row[dd]=='a':
       return 'a'
   return 'b'

但我正在寻找一种可以跨越 n 个列进行扩展的解决方案。

感谢任何帮助!


也许你可以只使用 df.iloc[:,:4].min(1) - Zero
1个回答

4

使用numpy.where,结合eq(==)条件和any函数,在每行中检查至少有一个True值:

cols = ['aa','bb','cc', 'dd']
df['ff'] = np.where(df[cols].eq('a').any(1), 'a', 'b')
print (df)
  aa bb cc dd   ee ff
0  a  a  b  b  foo  a
1  a  b  a  a  foo  a
2  b  a  a  a  bar  a
3  b  b  b  b  bar  b

细节:

print (df[cols].eq('a'))
      aa     bb     cc
0   True   True  False
1   True  False   True
2  False   True   True
3  False  False  False

print (df[cols].eq('a').any(1))
0     True
1     True
2     True
3    False
dtype: bool

如果需要自定义功能:

def some_function(row):
   if row[cols].eq('a').any():
       return 'a'
   return 'b'

df['ff'] = df.apply(some_function, 1)
print (df)
  aa bb cc dd   ee ff
0  a  a  b  b  foo  a
1  a  b  a  a  foo  a
2  b  a  a  a  bar  a
3  b  b  b  b  bar  b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接