【问题标题】:How Do I Find a Specific Expression within a Dataframe Column? [duplicate]如何在数据框列中查找特定表达式? [复制]
【发布时间】:2018-08-07 17:01:30
【问题描述】:

我有一个数据框,其中有一列名为“描述”。我想浏览此列中的所有文本,并确定那些描述包含至少 3 位数字的行。

这是我所在的位置:

import re 
df['StrDesc'] = df['Description'].str.split()
y=re.findall('[0-9]{3}',str(df['StrDesc'])
print(y)

我将文本列转换为字符串。在使用最终的正则表达式之前,我是否需要运行一个 for 循环来遍历每一行?

我这样做是最好的吗?

我的错误是“解析时出现意外的 EOF。”

【问题讨论】:

  • 您在第三行末尾缺少括号。

标签: python regex


【解决方案1】:

不需要使用str.findallsplit

y = df['Description'].str.findall('[0-9]{3}')

但是通过一些测试general solution 有点复杂:

df = pd.DataFrame({'Description':['354 64 133 5867 4 te345',
                                  'rt34 3tyr 456',
                                  '23 gh346h rt 9404']})

print(df)
               Description
0  354 64 133 5867 4 te345
1            rt34 3tyr 456
2        23 gh346h rt 9404

y = df['Description'].str.findall('(?:(?<!\d)\d{3}(?!\d))')
print (y)
0    [354, 133, 345]
1              [456]
2              [346]
Name: Description, dtype: object

【讨论】:

  • 使用 panda 的内置 str 操作和正则表达式绝对是要走的路。
  • @PMende - 绝对同意 ;)
  • 谢谢大家!我在想它比它更复杂。我使用了 jezrael 单行代码。
猜你喜欢
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2021-05-16
  • 2022-11-23
  • 2018-08-20
  • 2019-12-29
  • 1970-01-01
相关资源
最近更新 更多