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

时间:2017-10-18 11:29:55

标签: python pandas

我有一个像这样的pandas数据框:

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列数的解决方案。

感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

使用eq创建由True(==)与numpy.where创建的条件来检查每行至少一个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

如果需要自定义功能:

Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
相关问题