python - 检查一列是否包含来自其他列的值并填充第三列(真或假)
问题描述
我想检查一列是否包含来自其他列的值,并用 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:“系列”对象是可变的,因此它们不能被散列
非常感谢任何帮助!
解决方案
对于测试是否包含每行的值,请使用apply
within
对于布尔值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.nan
is 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')
推荐阅读
- spring-security-oauth2 - "Full authentication is required to access this resource
- python - Getting AttributeError: __exit__ when working with Tensorflow and MNIST data
- c# - What is wrong with my aproach for detecting open serial port?
- sql - Comparing two latest rows and return true or false based on location_id
- excel - application function using index small if in order to find more than one matching result
- c# - 为什么我没有得到 EnvironmentVariable
- .net - Firebase 云函数:你可以从 dll 调用函数吗?
- sass - Is the a way to create a large list in SCSS?
- vectorization - Matrix multiplication with vectorization in c++
- java - 如何更改 JComboBox 的字体