【问题标题】:how to check whether column of text contains specific string or not in pandas如何在熊猫中检查文本列是否包含特定字符串
【发布时间】:2019-10-11 15:11:44
【问题描述】:

我在熊猫中有以下数据框

 job_desig             salary
 senior analyst        12
 junior researcher     5
 scientist             20
 sr analyst            12

现在我想生成一列,其标志设置如下

 sr = ['senior','sr']
 job_desig             salary     senior_profile
 senior analyst        12         1  
 junior researcher     5          0
 scientist             20         0 
 sr analyst            12         1

我正在关注熊猫

 df['senior_profile'] = [1 if x.str.contains(sr) else 0 for x in 
                        df['job_desig']]

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以通过| 连接列表的所有值,用于正则表达式OR,传递给Series.str.contains,最后转换为整数,用于True/False1/0 的映射:

df['senior_profile'] = df['job_desig'].str.contains('|'.join(sr)).astype(int)

如有必要,使用单词边界:

pat = '|'.join(r"\b{}\b".format(x) for x in sr)
df['senior_profile'] = df['job_desig'].str.contains(pat).astype(int)

print (df)
           job_desig  salary  senior_profile
0     senior analyst      12               1
1  junior researcher       5               0
2          scientist      20               0
3         sr analyst      12               1

如果列表中只有一个单词的值,则带有集合的解决方案:

df['senior_profile'] = [int(bool(set(sr).intersection(x.split()))) for x in df['job_desig']]

【讨论】:

    【解决方案2】:

    您只需使用str.contains就可以做到这一点

    df['senior_profile'] = df['job_desig'].str.contains('senior') | df['job_desig'].str.contains('sr')
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2013-02-24
      • 2021-07-12
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多