我有一个看起来像这样的数据集:
index Ind. Code Code_2
1 1 NaN x
2 0 7 NaN
3 1 9 z
4 1 NaN a
5 0 11 NaN
6 1 4 NaN
我还创建了一个列表来指示代码列中的值,如下所示:
Code_List=['7', '9', '11']
我想为指标创建一个新列,只要 Ind. = 1,Code 在上面的列表中,并且 Code 2 不为空,该列就为 1
我想创建一个包含 if 语句的函数。我尝试了这个,不确定是否是语法问题,但我不断收到如下属性错误:
def New_Indicator(x):
if x['Ind.'] == 1 and (x['Code'].isin[Code_List]) or (x['Code_2'].notnull()):
return 1
else:
return 0
df['NewIndColumn'] = df.apply(lambda x: New_Indicator(x), axis=1)
("'str
' object has no attribute 'isin
'", 'occurred at index 259') ("'float
' object has no attribute 'notnull
'", 'occurred at index 259')
问题是在你的函数中,x['Code']
是一个字符串,而不是一个Series。我建议您使用numpy.where :
ind1 = df['Ind.'].eq(1)
codes = df.Code.isin(code_list)
code2NotNull = df.Code_2.notnull()
mask = ind1 & codes & code2NotNull
df['indicator'] = np.where(mask, 1, 0)
print(df)
输出
index Ind. Code Code_2 indicator
0 1 1 NaN x 0
1 2 0 7.0 NaN 0
2 3 1 9.0 z 1
3 4 1 NaN a 0
4 5 0 11.0 NaN 0
5 6 1 4.0 NaN 0
更新(按照@splash58的建议):
df['indicator'] = mask.astype(int)
我是一名优秀的程序员,十分优秀!