【问题标题】:Filter for a string followed by a random row of numbers过滤后跟随机数字行的字符串
【发布时间】:2019-09-18 00:19:19
【问题描述】:

我想在数据框中过滤一行。

ch=b611067=football

我的问题是我只想过滤 b'611067 部分。

我知道我可以使用关注 str.startswith('b') 来查找 ID 的开头,但我正在寻找的是一种表达方式,例如 str.contains('random 6 digit numberical value'

希望这是有道理的。

【问题讨论】:

  • 不熟悉熊猫。如果您可以使用正则表达式,请尝试使用 'b[0-9]{6}' 之类的模式
  • 谢谢,我试试看。
  • 是否可以添加一些示例数据,以便我们为您重现解决方案?
  • 您好,我已经尝试了 'b[0-9]{6}' 并且成功了!

标签: python pandas


【解决方案1】:

我(还)不确定如何在 pandas 中有效地做到这一点,但您可以使用正则表达式进行匹配:

import re

pattern = '(b\d{6})'
text = 'ch=b611067=football'
matches = re.findall(pattern=pattern, string=text)
for match in matches:
    pass # do something

编辑:这个答案解释了如何将正则表达式与熊猫一起使用: How to filter rows in pandas by regex

【讨论】:

    【解决方案2】:

    您可以使用.str 访问器在字符串列上使用字符串函数,包括通过正则表达式匹配:

    import pandas as pd
    df = pd.DataFrame(data={"foo": ["us=b611068=handball", "ch=b611067=football", "de=b611069=hockey"]})
    print(df.foo.str.match(r'.+=b611067=.+'))
    

    输出:

    0    False
    1     True
    2     False
    Name: foo, dtype: bool
    

    您可以使用它来索引数据框,例如:

    print(df[df.foo.str.match(r'.+=b611067=.+')])
    

    输出:

                       foo
    1  ch=b611067=football
    

    如果你想要所有匹配模式b<6 numbers>的行,你可以使用tobias_k提供的表达式:

    df.foo.str.match(r'.+=b[0-9]{6}=.+')
    

    注意,这给出了与df.foo.str.contains(r'=b611067=') 相同的结果,它不需要您提供通配符并且是How to filter rows in pandas by regex 中给出的解决方案,但正如Pandas docs 中提到的那样,您可以使用match更严格。

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2021-12-06
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多