为什么我无法在熊猫中获得正确的口罩栏

时间:2020-03-16 13:28:15

标签: python pandas apply where-clause

例如,如果我有数据框

    x   f
0   0   [0, 1]
1   1   [3]
2   2   [2, 3, 4]
3   3   [3, 6]
4   4   [4, 5]

如果我想删除x不在f列中的行,我尝试在哪里应用,但无法获得预期的结果。我得到了下表,我想知道为什么行0、2、3是0而不是1?

    x   f   mask
0   0   [0, 1]  0
1   1   [3] 0
2   2   [2, 3, 4]   0
3   3   [3, 6]  0
4   4   [4, 5]  0

有人知道为什么吗?我应该怎么处理这个数字与列表的情况?

df1 = pd.DataFrame({'x': [0,1,2,3,4],'f' :[[0,1],[3],[2,3,4],[3,6],[3,5]]}, index = [0,1,2,3,4])
df1['mask'] = np.where(df1.x.values in df1.f.values ,1,0)

2 个答案:

答案 0 :(得分:3)

这是成对的必要测试值-列表理解中的import re from itertools import count c = count(1) s = "Hello, world" print(re.sub(r"o", lambda x: "{}".format(next(c)), s)) #or print(re.sub(r"o", lambda x: f"{next(c)}", s)) # --> Hell1, w2rld 解决方案:

in

或者使用DataFrame.applydf1['mask'] = np.where([a in b for a, b in df1[['x', 'f']].values],1,0)

axis=1

df1['mask'] = np.where(df1.apply(lambda x: x.x in x.f, axis=1),1,0)

答案 1 :(得分:2)

IIUC行爆炸,然后使用isin

pd.DataFrame(df1.f.tolist()).isin(df1.x).any(1).astype(int)
Out[10]: 
0    1
1    0
2    1
3    1
4    0
dtype: int32
df1['mask'] = pd.DataFrame(df1.f.tolist()).isin(df1.x).any(1).astype(int)
相关问题