首页 > 解决方案 > 检查一列是否包含来自其他列的值并填充第三列(真或假)

问题描述

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

df 在:

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:“系列”对象没有属性“包含”

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

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

非常感谢任何帮助!

标签: pythonpython-3.xpandas

解决方案


对于测试是否包含每行的值,请使用applywithin

对于布尔值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.nanis False,因此添加了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')

推荐阅读