2017-10-18 158 views
1

功能我有一个数据帧是这样的:大熊猫与ISIN

aa  bb cc 
[a, x, y] a 1 
[b, d, z] b 2 
[c, e, f] s 3 
np.nan d 4 

我想创建这样一个新列:

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 

我目前的解决办法是:

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) 

但是这会抛出一个错误("'str' object has no attribute 'isin'", 'occurred at index 0')

我怀疑,因为我在检查isin时错过了一些东西。

本质上,我需要检查bb的str值是否在列aa,它在每个单元格中都有一个列表。

有关如何做到这一点的任何想法?

回答

2

您在列表需要的参数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 

编辑:

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 

或者:

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 

编辑:

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 
+0

噢谢谢@jezrael如果它是一个条件逻辑怎么样。即只有当df ['cc'] == 1? – Kvothe

+0

检查上次编辑。 – jezrael

+0

啊谢谢!只是最后一个问题。你将如何处理缺失的值?通常在df ['aa']中有空白值。我用这个例子更新了这个问题。 – Kvothe