【问题标题】:check element-wise for existence of string逐元素检查字符串是否存在
【发布时间】:2019-08-06 14:13:08
【问题描述】:

我正在寻找一种方法来检查一个字符串是否可以在另一个字符串中找到。 str.contains 只接受一个固定的字符串模式作为参数,我宁愿在两个字符串列之间进行元素比较。

import pandas as pd

df = pd.DataFrame({'long': ['sometext', 'someothertext', 'evenmoretext'],
               'short': ['some', 'other', 'stuff']})


# This fails:
df['short_in_long'] = df['long'].str.contains(df['short'])

预期输出:

[True, True, False]

【问题讨论】:

  • 您接受的答案几乎是另一个人的抄本。不确定应该鼓励这种事情。仅供参考。
  • 我接受了另一个答案只是因为你的(优秀的)在我的实际情况下不起作用。所以另一个似乎更笼统。
  • 不确定您指的是哪个版本的答案。另一个答案也会因 TypeError 而失败。就像我回复你的其他评论一样,str.contains 的初始编辑是错误的,因为检查是 not 元素明智的。例如,使用 contains 解决方案,您将在所有行中搜索“some”,而它应该只检查第一行。一般,但完全错误。
  • 您不必接受我的回答,但您应该检查/验证您决定接受的解决方案的正确性,一般与否……仅此而已。祝你有美好的一天:)
  • 我确实检查了它们,我接受了最终版本,而不是最初的(错误的)版本。你也有美好的一天:)

标签: python string pandas


【解决方案1】:

还有,

df['short_in_long'] = df['long'].str.contains('|'.join(df['short'].values))

更新: 我误解了这个问题。这是修正后的版本:

df['short_in_long'] = df['long'].apply(lambda x: True if x[1] in x[0] else False, axis =1)

【讨论】:

  • 这是我的第一个错误答案。 OP 需要检查每行的值。
  • 正如@jezrael 提到的,操作需要逐行检查(1-1 检查),而不是(1-n)检查
  • 谢谢。我已更正我的代码以进行一对一的逐行检查。
【解决方案2】:

检查numpy,它是逐行的:-)。

np.core.char.find(df.long.values.astype(str),df.short.values.astype(str))!=-1
Out[302]: array([ True,  True, False])

【讨论】:

  • 我用了numpy一口井。我正在尝试df['short_in_long'] = np.where(df['short'].str.contains(df['long']), True, False)。为什么这不能按行工作?
  • @Erfan isin 不会检查部分匹配 :-)
  • 抱歉,这是我的第二次尝试。我编辑了我的评论。
  • @Erfan 两部分,str.contain 不接受Series,第二,如果您使用连接字符串与sep = '|',当第三行有任何部分字符串,如someother ,第三行将在str.contain下返回为True
  • @Erfan 是的,这就是为什么当像 1-1 这样进行逐行检查时,我们不能使用 str.contains
【解决方案3】:

zip 使用列表推导:

df['short_in_long'] = [b in a for a, b in zip(df['long'], df['short'])]

print (df)
            long  short  short_in_long
0       sometext   some           True
1  someothertext  other           True
2   evenmoretext  stuff          False

【讨论】:

    【解决方案4】:

    这是列表推导的主要用例:

    # df['short_in_long'] = [y in x for x, y in df[['long', 'short']].values.tolist()]
    df['short_in_long'] = [y in x for x, y in df[['long', 'short']].values]
    df
    
                long  short  short_in_long
    0       sometext   some           True
    1  someothertext  other           True
    2   evenmoretext  stuff          False
    

    列表推导通常比字符串方法更快,因为开销较小。见For loops with pandas - When should I care?


    如果您的数据包含 NaN,您可以调用带有错误处理的函数:

    def try_check(haystack, needle):
        try:
            return needle in haystack
        except TypeError:
            return False
    
    df['short_in_long'] = [try_check(x, y) for x, y in df[['long', 'short']].values]
    

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2014-09-24
      • 1970-01-01
      • 2013-10-31
      • 2020-11-12
      • 2017-11-20
      • 2015-08-09
      • 2022-06-29
      • 2012-11-20
      相关资源
      最近更新 更多