【问题标题】:How to check if a string is in a longer string in pandas DataFrame?如何检查字符串是否在 pandas DataFrame 中的较长字符串中?
【发布时间】:2019-12-22 01:18:45
【问题描述】:

我知道使用df.str.contains() 检查列是否包含某个子字符串非常简单。

如果我想反其道而行之:检查列的值是否包含在较长的字符串中?我进行了搜索,但找不到答案。我认为这应该很容易,就像在纯 python 中我们可以简单地 'a' in 'abc'

我尝试使用df.isin,但似乎不是为此目的而设计的。

假设我的 df 看起来像这样:

       col1      col2
0     'apple'    'one'
1     'orange'   'two'
2     'banana'   'three'

我想在col1 上查询这个 df,如果 包含 字符串 appleorangefruits,它应该返回前两行。

【问题讨论】:

  • 你能不能创建minimal reproducible example,这会解释很多。
  • 您要检查较长的字符串是否为常数,还是因情况而异?
  • @harvpan 谢谢。添加了一个简单的例子
  • @KevinTroythanks 凯文。它会有所不同,例如,我在 df 中有一个名为 ID 的列。但不知何故,用户为我提供了另一种格式更长的 ID。我想迭代 ID 列表以找出那些匹配的行。

标签: python pandas dataframe


【解决方案1】:

由于apply 的速度非常慢,所以我想我可以尝试一些其他的想法。

如果你的“long_string”比较短,而你的 DataFrame 很大,你可以做一些奇怪的事情。

from itertools import combinations
from random import choice

# Create a large DataFrame
df = pd.DataFrame(
    data={'test' : [choice('abcdef') for i in range(10_000_000)]}
)

long_string = 'abcdnmlopqrtuvqwertyuiop'

def get_all_substrings(input_string):
    length = len(input_string)
    return [input_string[i:j + 1] for i in range(length) for j in range(i,length)]

sub_strings = get_all_substrings(long_string)

df.test.isin(sub_strings)

上述apply(lambda a: a in 'longer string') 答案的运行时间约为 300 毫秒,而 2.89 秒。这快了十倍!

注意:我使用了 How To Get All The Contiguous Substrings Of A String In Python? 中的 get_all_substrings 函数

【讨论】:

    【解决方案2】:

    您可以在列上调用apply,即:

    df['your col'].apply(lambda a: a in 'longer string')
    

    【讨论】:

      【解决方案3】:

      你需要:

      longstring = 'appleorangefruits'
      df.loc[df['col1'].apply(lambda x: x in longstring)]
      

      输出:

          col1    col2
      0   apple   one
      1   orange  two
      

      【讨论】:

        【解决方案4】:

        如果你检查的字符串是一个常量,我相信你可以使用DataFrame.apply来实现它:

        df.apply(lambda row: row['mycol'] in 'mystring', axis=1)

        【讨论】:

          【解决方案5】:

          试试..

          >>> df[df.col1.apply(lambda x: x in 'appleorangefruits')]
               col1 col2
          0   apple  one
          1  orange  two
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-08-01
            • 2019-10-03
            • 1970-01-01
            • 2017-10-31
            • 1970-01-01
            • 2013-01-09
            相关资源
            最近更新 更多