【问题标题】:Removing leading text characters from string in python从python中的字符串中删除前导文本字符
【发布时间】:2019-12-27 00:25:44
【问题描述】:
import pandas as pd
import re
df = pd.DataFrame({'fix_this_field':['dogstreet 1234, st, texas 57500', 'animal hospital of dallas, 233 medical ln '], 'needed solution':['1234, st texas 57500', '233 medical ln']})
df #look what i want

我想提取第一个数字之后的所有数据,包括数字。请参阅数据框中的解决方案列。所以像“hospital2019 lane”这样的东西会变成“2019 lane”。

我试着按照下面的路线寻找一些东西,但我正在挣扎,头撞在墙上。请让我知道我的方式错误。

x = 'hospital2019 lane'
r = re.compile("^([a-zA-Z]+)([0-9]+)")
m = r.match(x)
m.groups()
# it stops at 2019.   I want 2019 lane.....('hospital', '2019')

【问题讨论】:

  • 请展示你做了从这个正则表达式中得到了什么。
  • @Prune 已更新
  • 也许使用 for 循环每个字符与 try int() 除外?但是如果你有大数据集,这会很慢

标签: python regex pandas


【解决方案1】:

使用split很容易实现

df.fix_this_field.str.split('(\d)',1).str[1:].apply(''.join)
Out[475]: 
0    1234, st, texas 57500
1          233 medical ln 
Name: fix_this_field, dtype: object
df['col']=df.fix_this_field.str.split('(\d)',1).str[1:].apply(''.join)

【讨论】:

    【解决方案2】:

    如果你必须使用正则表达式,下面是一个尝试:

    • 正则表达式:(?:[a-zA-Z ])([0-9]+.*)
    reg = re.compile('(?:[a-zA-Z ,])([0-9]+.*)')
    
    def clean(col):
        return re.findall(reg, col)[0] if re.findall(reg, col) else None
    
    df.fix_this_field.apply(clean)
    
    Out[1]:
    0    1234, st, texas 57500
    1          233 medical ln 
    Name: fix_this_field, dtype: object
    

    【讨论】:

      【解决方案3】:

      我发现df.fix_this_field.apply(lambda x: x[re.search("\d",x).start():])df.fix_this_field.apply(lambda x: ''.join(re.split('(\d)',x,1)[1:])) 的速度是df.fix_this_field.str.split('(\d)',1).str[1:].apply(''.join) 的几倍。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2011-07-25
        • 1970-01-01
        相关资源
        最近更新 更多