gpt4 book ai didi

python - 如果函数 : if column A==1 AND 1 column B is in list X and column C is not null, 1。否则,0

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:02 24 4
gpt4 key购买 nike

我有一个看起来像这样的数据集:

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) 

关于python - 如果函数 : if column A==1 AND 1 column B is in list X and column C is not null, 1。否则,0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58614583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com