gpt4 book ai didi

python - 使用系列中的字符串检查 pandas 中的 str.contains

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:07 24 4
gpt4 key购买 nike

为什么这不适用于使用 pandas 的字符串方法?

df['col1'].str.contains(df['col2'])

继续获取:“Series”对象是可变的,因此它们不能被散列。

更新:澄清一下——我会逐行比较这些列,并使部分字符串按顺序完全匹配。例如,对于下面的第 1 列和第 2 列,我希望上面的输出与输出中的一样:

col-1    col-2    output
'cat' 'at' True
'aunt' 'at' False
'dog' 'dg' False
'edge' 'dg' True

最佳答案

您可以定义一个简单的函数,并只使用一个测试来判断一列中的一个值是否在另一列中:

In [37]:

df = pd.DataFrame({'col1':['mn','mxn','ca','sd','xa','ac'], 'col2':['m','n','x','n','q','y']})
def func(x):
return x.col2 in list(x.col1)
df.apply(func, axis=1)
Out[37]:
0 True
1 True
2 False
3 False
4 False
5 False
dtype: bool

对于您的用例,以下应该满足您的要求:

return x.col2 in x.col1

关于python - 使用系列中的字符串检查 pandas 中的 str.contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726168/

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