【问题标题】:search for a partial string from list and add column with that parital str从列表中搜索部分字符串并添加具有该部分字符串的列
【发布时间】:2017-11-02 18:11:05
【问题描述】:

我不会在 df.column 中搜索我保存在一个系列中的部分字符串,也不会使用我在每一行中找到的 str 创建一个新列。我的部分问题已解决 pandas: test if string contains one of the substrings in a list

例如,假设我有系列 s = pd.Series(['cat','hat','dog','fog','pet']),我想找到所有包含 s 的地方['og', 'at'] 中的任何一个,我都想得到除了宠物之外的所有东西。

解决办法是:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

但我想得到

         pet    contains
    0    cat    at
    1    hat    at
    2    dog    og
    3    fog    og
    dtype: object

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用extract,如果没有匹配得到NaNs,所以添加dropna

    searchfor = ['og', 'at']
    df['new'] = df['pet'].str.extract('(' + '|'.join(searchfor) + ')', expand=False)
    df = df.dropna(subset=['new'])
    print (df)
       pet contains1 new
    0  cat        at  at
    1  hat        at  at
    2  dog        og  og
    3  fog        og  og
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-15
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多