【问题标题】:return all substrings from a list of strings in a dataframe column [duplicate]从数据框列中的字符串列表中返回所有子字符串[重复]
【发布时间】:2019-09-15 23:14:53
【问题描述】:

我需要搜索 df 列并从列表中返回所有子字符串。

myList= ['a cat', 'the dog', 'a cow']

example df
'col A'
there was a cat with the dog
the cow was brown
the dog was sick

这会拆分列表中的单词并且只返回单个单词

df['col B'] = df['col A'].apply(lambda x: ';'.join([word for word in x.split() if word in (myList)]))

还尝试添加一个 np any...

df['col B'] = df['col A'].apply(lambda x: ';'.join(np.any(word for word in df['col A'] if word in (myList))))

需要退货

'col B'
a cat;the dog
NaN
the dog

【问题讨论】:

    标签: python pandas numpy lambda


    【解决方案1】:

    你可以

    s = df.col.str.extractall(f'({"|".join(myList)})')
    res = s.groupby(s.index.get_level_values(0))[0].agg(';'.join)
    df.loc[res.index, 'new'] = res
    

                                col            new
    0  there was a cat with the dog  a cat;the dog
    1             the cow was brown            NaN
    2              the dog was sick        the dog
    

    【讨论】:

      【解决方案2】:

      这应该可行,你已经接近了:

      import numpy as np
      
      df['col B'] = df['col A'].apply(lambda x: ';'.join([m for m in myList if m in x])).replace('',np.nan)
      

      结果:

                                col A          col B
      0  there was a cat with the dog  a cat;the dog
      1             the cow was brown            NaN
      2              the dog was sick        the dog
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-05
        • 2021-08-14
        • 2020-06-01
        • 2021-08-31
        • 2021-12-18
        • 2023-03-28
        • 2015-05-07
        • 2021-12-31
        相关资源
        最近更新 更多