【问题标题】:Pandas: select rows from columns using RegexPandas:使用正则表达式从列中选择行
【发布时间】:2016-12-04 10:12:05
【问题描述】:

我想从feccandid 列中提取第一个值为 H 或 S 的行:

    cid     amount  date    catcode     feccandid
0   N00031317   1000    2010    B2000   H0FL19080
1   N00027464   5000    2009    B1000   H6IA01098
2   N00024875   1000    2009    A5200   S2IL08088
3   N00030957   2000    2010    J2200   S0TN04195
4   N00026591   1000    2009    F3300   S4KY06072
5   N00031317   1000    2010    B2000   P0FL19080
6   N00027464   5000    2009    B1000   P6IA01098
7   N00024875   1000    2009    A5200   S2IL08088
8   N00030957   2000    2010    J2200   H0TN04195
9   N00026591   1000    2009    F3300   H4KY06072

我正在使用此代码:

campaign_contributions.loc[campaign_contributions['feccandid'].astype(str).str.extractall(r'^(?:S|H)')]

返回错误: ValueError: pattern contains no capture groups

有使用 Regex 经验的人知道我做错了什么吗?

【问题讨论】:

    标签: regex pandas


    【解决方案1】:

    对于这么简单的事情,你可以绕过正则表达式:

    relevant = campaign_contributions.feccandid.str.startswith('H') | \
        campaign_contributions.feccandid.str.startswith('S')
    campaign_contributions[relevant]
    

    但是,如果您想使用正则表达式,您可以将其更改为

    relevant = ~campaign_contributions['feccandid'].str.extract(r'^(S|H)').isnull()
    

    注意astype是多余的,extract就足够了。

    【讨论】:

      【解决方案2】:

      为什么不直接使用str.match 而不是提取和否定?

      df[df['col'].str.match(r'^(S|H)')]

      (我来这里是为了寻找相同的答案,但 extract 的使用似乎很奇怪,所以我找到了 str.ops 的文档。

      W

      【讨论】:

      • 虽然两个答案都有效,但这是一个更好的解决方案。
      猜你喜欢
      • 2012-11-21
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多