熊猫根据缺失值的条件逻辑添加新列

科沃特

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

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

我想创建一个新列,df['ff']如:

aa bb   cc dd ee   ff
a  a    b  b  foo  c
a  b    a  a  foo  c
a  nan  a  a  bar  d
a  b    b  b  bar  c

逻辑是: if df['bb'] is not null and df['aa']==a, then c else d

根据其他问题的答案,我认为答案应该是这样的:

df['ff'] = df.apply(lambda x: x['bb'].isnull(),axis=1) & (x['aa']=='a')

但我收到这样的错误:

("'str' object has no attribute 'isnull'", 'occurred at index 0')

最大U

我会使用以下矢量化方法:

In [47]: df['ff'] = np.where(df['bb'].notnull() & df['aa'].eq('a'), 'c', 'd')

In [48]: df
Out[48]:
  aa   bb cc dd   ee ff
0  a    a  b  b  foo  c
1  a    b  a  a  foo  c
2  b  NaN  a  a  bar  d
3  b    b  b  b  bar  d

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章