gpt4 book ai didi

python - 检查一列是否包含其他列的值并填充第三列(真或假)

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:16 25 4
gpt4 key购买 nike

我想检查一列是否包含来自其他列的值,并用 True 或 False 填充第三列。

输入:

id | name  | account
-------------------
01 | John | AB01
02 | Emma | AB03
03 | Alice | AB03

df 输出:

id | name  | account | match
----------------------------
01 | John | AB01 | True
02 | Emma | AB03 | False
03 | Alice | AB03 | True

我已经试过了:

df['match'] = np.where(df['account'].contains(df['id']), 'True','False')

错误:AttributeError:“系列”对象没有属性“包含”

df['match'] = np.where(df['account'].str.contains(df['id']), 'True','False')

错误:TypeError:'Series' 对象是可变的,因此它们不能被散列

非常感谢任何帮助!

最佳答案

要测试每行是否包含值,请使用 applyin

对于 bool 值True, False:

df['match'] =  df.apply(lambda x: x['id'] in x['account'], axis=1)

对于字符串 'True', 'False':

df['match'] =  np.where(df.apply(lambda x: x['id'] in x['account'], axis=1), 'True','False')


print (df)
id name account match
0 01 John AB01 True
1 02 Emma AB03 False
2 03 Alice AB03 True

编辑:

有缺失值,所以可能的解决方案是使用 np.nan == np.nanFalse,所以添加了 if-else声明:

print (df)
id name account
0 01 John AB01
1 02 Emma NaN
2 03 Alice AB03

对于 bool 值True, False:

df['match'] = df.apply(lambda x: x['id'] in x['account'] 
if x['account'] == x['account']
else False, axis=1)

对于字符串 'True', 'False':

df['match'] = np.where(df.apply(lambda x: x['id'] in x['account'] 
if x['account'] == x['account']
else False, axis=1), 'True','False')
print (df)
id name account match
0 01 John AB01 True
1 02 Emma NaN False
2 03 Alice AB03 True

另一个想法是使用带有 try-exception 语句的自定义函数:

def test(x):
try:
return x['id'] in x['account']
except Exception:
return False

对于 bool 值True, False:

df['match'] = df.apply(test, axis=1)

对于字符串 'True', 'False':

df['match'] = np.where(df.apply(test, axis=1), 'True','False')

关于python - 检查一列是否包含其他列的值并填充第三列(真或假),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57955306/

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