python-3.x - 检查列值是否在另一列中,哪些值是列表

标签 python-3.x pandas

我在数据框中有两列。第一个在每一行中包含一个字符串。第二个包含每行的一组字符串。我如何检查每一行的第一列的值是否在使用 Pandas 函数的第二列中,并且它的效率?

pd.DataFrame([np.random.randint(5, size=12), np.random.randint(5, size=(12,5))]).T

enter image description here

如何检查第 1 列列表中第 0 列的值

最佳答案

使用列表理解和 zip (IMO 这将比 apply 更快):

df=df.assign(Check=[a in b for a,b in zip(df[0],df[1])])
    0                1  Check
0   4  [4, 4, 2, 3, 0]   True
1   4  [1, 0, 2, 1, 4]   True
2   0  [2, 1, 1, 2, 2]  False
3   0  [0, 3, 3, 2, 3]   True
4   4  [3, 0, 0, 3, 1]  False
5   1  [0, 2, 0, 3, 4]  False
6   0  [4, 3, 4, 1, 1]  False
7   1  [2, 0, 0, 3, 1]   True
8   2  [3, 3, 3, 2, 4]   True
9   2  [3, 0, 0, 4, 1]  False
10  0  [3, 3, 3, 4, 3]  False
11  1  [0, 3, 3, 2, 1]   True

在测试数据上的表现:

enter image description here

关于python-3.x - 检查列值是否在另一列中,哪些值是列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57340425/

相关文章:

python-3.x - 卡在带有 urllib (python3) 的打开网址上

python - Pandas 应用处理比现有数据框更多的行

python - 将二维数组转换为 [ [ x0 y0 ] [x1 y1] [x2 y2] ] 形式

python - 追加在程序中多次调用时会返回语法错误

python-3.x - 安装readline后python 3.6崩溃

python - 根据 Pandas 中另一列的值添加新列(python)

python - Pandas 和 Cassandra : numpy array format incompatibility

python - 如何在 python 中编写嵌套并发代码?

python - 按周和 ID 分组、求平均值、再次按周分组并绘图

python - 减去单独列等于特定值的列