我有一个这样的数据帧:
aa bb cc
[a, x, y] a 1
[b, d, z] b 2
[c, e, f] s 3
np.nan d 4
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个这样的新列:
aa bb cc dd
[a, x, y] a 1 True
[b, d, z] b 2 True
[c, e, f] s 3 False
np.nan d 4 False
Run Code Online (Sandbox Code Playgroud)
我目前的解决方案是:
def some_function(row):
if row['bb].isin(row['aa'])==True:
return True
return False
df['dd'] = df.apply(lambda row: some_function(row), axis=1)
Run Code Online (Sandbox Code Playgroud)
但这会引发错误 ("'str' object has no attribute 'isin'", 'occurred at index 0')
我怀疑,因为我在检查时错过了一些东西isin.
基本上,我需要检查str值bb是否在列aa中,每个单元格中都有一个列表.
关于如何做到这一点的任何想法?
您需要in列表中的检查成员资格的参数:
df['dd'] = df.apply(lambda x: x.bb in x.aa, axis=1)
print (df)
aa bb cc dd
0 [a, x, y] a 1 True
1 [b, d, z] b 2 True
2 [c, e, f] s 3 False
Run Code Online (Sandbox Code Playgroud)
编辑:
df['dd'] = df.apply(lambda x: (x.bb in x.aa) and (x.cc == 1), axis=1)
print (df)
aa bb cc dd
0 [a, x, y] a 1 True
1 [b, d, z] b 2 False
2 [c, e, f] s 3 False
Run Code Online (Sandbox Code Playgroud)
要么:
df['dd'] = df.apply(lambda x: x.bb in x.aa, axis=1) & (df['cc'] == 1)
print (df)
aa bb cc dd
0 [a, x, y] a 1 True
1 [b, d, z] b 2 False
2 [c, e, f] s 3 False
Run Code Online (Sandbox Code Playgroud)
编辑:
df['dd'] = df.apply(lambda x: x.bb in x.aa if type(x.aa) == list else False, axis=1)
print (df)
aa bb cc dd
0 [a, x, y] a 1 True
1 [b, d, z] b 2 True
2 [c, e, f] s 3 False
4 NaN d 4 False
Run Code Online (Sandbox Code Playgroud)