我有一个 pandas 数据框,如下所示,
我想检查 items_check1
中是否有项目存在于 all_items
或不,然后将此结果保存到单独的列中: check1_output
;然后想用 items_check2
再次重复相同的过程和all_items
;并将其保存到 check2_output
.
所以[所需的输出]应该是这样的,
我有数十亿行,有时单个单元格中的项目数为 all_items
最多可包含 100 项。我正在寻找完成此比较的最有效方法。
到目前为止的尝试
以下是我尝试过的,与迭代行相比,这更有效,但我很快发现输出并不总是符合预期。这种行为的可能原因是什么?
df['check1_output'] = np.where([x[0] in x[1] for x in zip(df['items_check1'], df['all_items'])], True, False)
df['check2_output'] = np.where([x[0] in x[1] for x in zip(df['items_check2'], df['all_items'])], True, False)
[实际输出]
这是重新生成上述数据帧的片段
df = pd.DataFrame({'id': [1239,3298,9384],
'all_items': ['foobar,foo,foofoo,bar','foobar,foo','foo,bar'],
'items_check1': ['foo,bar','foobar','barfoo'],
'items_check2': ['foobar','bar','bar']
})
编辑: 添加计算时间
我提到的方法采用 610µs
3 行数据帧的时间。但当我在包含数十亿条记录的实际数据上运行它时,需要花费很多小时。因此寻找一种更有效的方法。
最佳答案
尝试将 issubset()
与 str.split()
结合使用:
df["check1_output"] = df.apply(lambda x: set(x["items_check1"].split(",")).issubset(x["all_items"].split(",")), axis=1)
df["check2_output"] = df.apply(lambda x: set(x["items_check2"].split(",")).issubset(x["all_items"].split(",")), axis=1)
>>> df
id all_items ... check1_output check2_output
0 1239 foobar,foo,foofoo,bar ... True True
1 3298 foobar,foo ... True False
2 9384 foo,bar ... False True
关于python - 检查 Pandas 中另一列值中是否存在字符串的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68004927/