pandas基于缺失值的条件逻辑添加新列

2024-04-18 22:50:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个pandas数据帧:

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'],如下所示:

^{pr2}$

逻辑是: 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')


Tags: 数据pandasdffoobar逻辑nandd
1条回答
网友
1楼 · 发布于 2024-04-18 22:50:02

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

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

相关问题 更多 >