【问题标题】:Regular Expression to extract numbers from age range DataFrame column with multiple formats正则表达式从具有多种格式的年龄范围 DataFrame 列中提取数字
【发布时间】:2019-02-27 17:31:17
【问题描述】:

我正在尝试从具有多种格式的列中提取高数和低数。

例如,

  • 如果值为:'Age 34 - 35',我要收集(34, 35)
  • 如果值为:'35-44岁',我要收集(35, 44)
  • 如果值为:'75+岁,我很好收集(75,'')

我目前编写了一个适用于某些格式但不适用于其他格式的正则表达式:

dataframe[['age_low', 'age_high]] = dataframe['age'].str.extract(r'(\d*)[\s-]*(\d*)')

以下是原始年龄列中所有可能的值:

dataframe['age'].unique()

array([nan, 'Age 34 - 35 ', 'Age 78 - 79 ', 'Age 60 - 61 ',
       'Age 50 - 51 ', 'Age 20 - 21 ', 'Age 70 - 71 ', 'Age 82 - 83 ',
       'Age 88 - 89 ', 'Age 68 - 69 ', 'Age 86 - 87 ', 'Age 84 - 85 ',
       'Age 46 - 47 ', 'Age 30 - 31', 'Age 94 - 95 ', 'Age 22 - 23 ',
       'Age 44 - 45 ', 'Age 74 - 75 ', 'Age 40 - 41', 'Age 72 - 73 ',
       'Age 52 - 53 ', 'Age 48 - 49 ', 'Age 66 - 67 ', 'Age 62 - 63 ',
       'Age 56 - 57 ', 'Age 64 - 65 ', 'Age 38 - 39 ', 'Age 42 - 43 ',
       'Age 54 - 55 ', 'Age 24 - 25 ', 'Age 90 - 91 ', 'Age 76 - 77 ',
       'Age 58 - 59 ', 'Age 32 - 33', 'Age 26 - 27 ', 'Age 80 - 81 ',
       'Age 28 - 29 ', 'Age 36 - 37', 'Age 96 - 97 ',
       'Age greater than 99', 'Age 18 - 19', 'Age 92 - 93 ',
       'Age 98 - 99 ','65-74 years old', '35-44 years old', '45-54 years old',
       '75+ years old', '55-64 years old', '25-34 years old',
       '18-24 years old'], dtype=object)

【问题讨论】:

  • 试试r'(\d+)(?:[\s-]*(\d+))?'r'(\d+)[\s-]*(\d*)'

标签: python regex pandas


【解决方案1】:

对于您的问题中只有一个年龄值的可能值,该年龄始终代表范围的低端。因此,您可以只捕获字符串中的第一个或多个数字,然后使用非捕获组来指示潜在的后续非数字序列,然后是另一组一个或多个数字。如果字符串中有第二个年龄,它将被捕获为范围的高端。如果只有一个年龄,您将只获得范围高端的NaN 值。

例如:

import pandas as pd

ages = ['Age 96 - 97', 'Age greater than 99', '65-74 years old', '75+ years old']
df = pd.DataFrame({'age': ages})

df[['age_low', 'age_high']] = df['age'].str.extract(r'(\d+)(?:\D+(\d+))?')
print(df)
#                    age age_low age_high
# 0          Age 96 - 97      96       97
# 1  Age greater than 99      99      NaN
# 2      65-74 years old      65       74
# 3        75+ years old      75      NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多