gpt4 book ai didi

python - 为什么我无法在 pandas 中获得正确的掩码列

转载 作者:行者123 更新时间:2023-12-01 20:13:11 26 4
gpt4 key购买 nike

例如,如果我有一个数据框

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

如果我想删除 x 列不在 f 列中的行,我尝试使用 where 和 apply 但无法获得预期结果。我得到了下表,我想知道为什么第 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)

最佳答案

这里是必要的成对测试值 - 列表理解中使用 in 的解决方案:

df1['mask'] = np.where([a in b for a, b in df1[['x', 'f']].values],1,0)

或者使用 DataFrame.applyaxis=1:

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

print (df1)
x f mask
0 0 [0, 1] 1
1 1 [3] 0
2 2 [2, 3, 4] 1
3 3 [3, 6] 1
4 4 [3, 5] 0

关于python - 为什么我无法在 pandas 中获得正确的掩码列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60706898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com