检查列是否包含来自其他列的值,并填写第三列(真或假)

2024-10-16 22:29:43 发布

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

我想检查一列是否包含另一列的值,并用True或False填充第三列。你知道吗

数据框输入:

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

数据框输出:

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:“Series”对象没有“contains”属性

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

错误:TypeError:“Series”对象是可变的,因此不能对它们进行哈希运算

非常感谢您的帮助!你知道吗


Tags: 数据nameidfalsetruedfmatchnp
2条回答

像这样的?你知道吗

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

对于测试,如果每行包含值,则使用applyin

对于布尔值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

对于布尔值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

对于布尔值True, False

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

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

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

相关问题 更多 >