【问题标题】:Extracting Age values from text to create new column in pandas从文本中提取年龄值以在熊猫中创建新列
【发布时间】:2018-07-29 09:03:03
【问题描述】:

我有一个数据集如下:

df=pd.DataFrame([["Sam is 5", 2000],["John is 3 years and 6 months",1200],["Jack is 4.5 years",7000],["Shane is 25 years old",2000]], columns = ['texts','amount'])

print(df)

    texts                          amount
0   Sam is 5                        2000
1   John is 3 years and 6 months    1200
2   Jack is 4.5 years               7000
3   Shane is 25 years old           2000

我想从df['texts'] 中提取年龄值并用它来计算新列df['value']

df['value'] = df['amount'] / val 

其中 val 是来自 df['texts'] 的数值

这是我的代码

val = df['texts'].str.extract('(\d+\.?\d*)', expand=False).astype(float)
df['value'] = df['amount']/val
print(df)

输出:

    texts                          amount     value
0   Sam is 5                       2000     400.000000
1   John is 3 years and 6 months   1200     400.000000
2   Jack is 4.5 years              7000     1555.555556
3   Shane is 25 years old          2000     80.000000

预期输出:

    texts                          amount     value
0   Sam is 5                       2000     400.000000
1   John is 3 years and 6 months   1200     342.85
2   Jack is 4.5 years              7000     1555.555556
3   Shane is 25 years old          2000     80.000000

上述代码中的问题是我无法弄清楚如何将 3 年 6 个月转换为 3.5 年。

附加信息:文本列仅包含年龄值,也按年份和月份排列。

欢迎提出任何建议。谢谢

【问题讨论】:

  • 3 年零 6 个月不是 3.6 年。
  • 我觉得你应该为每个人存储一个绝对数字,例如生日,然后据此计算。
  • @DyZ 是 3.5 年。
  • 您的表达式返回 3.0,因为它忽略了“6 个月”。你需要一个像'(\d+)(:?\.\d*)?\D+(\d*)' 这样的正则表达式。

标签: python regex python-3.x pandas


【解决方案1】:

我相信你需要:

注意:如果没有年份和月份文本,则解决方案以年份计算

#extract all first numbers
a = df['texts'].str.extract('(\d+\.?\d*)', expand=False).astype(float)
#extract years only
b = df['texts'].str.extract('(\d+\.?\d*)\s+years', expand=False).astype(float)
#replace NaNs by a
y = b.combine_first(a)
print(y)
0     5.0
1     3.0
2     4.5
3    25.0
Name: texts, dtype: float64

#extract months only
m = df['texts'].str.extract('(\d+\.?\d*)\s+months', expand=False).astype(float) / 12
print (m)
0    NaN
1    0.5
2    NaN
3    NaN
Name: texts, dtype: float64

#add together
val = y.add(m, fill_value=0)
print (val)
0     5.0
1     3.5
2     4.5
3    25.0
Name: texts, dtype: float64

df['value'] = df['amount']/val
print (df)
                          texts  amount        value
0                      Sam is 5    2000   400.000000
1  John is 3 years and 6 months    1200   342.857143
2             Jack is 4.5 years    7000  1555.555556
3         Shane is 25 years old    2000    80.000000

【讨论】:

  • 谢谢。这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2020-03-26
  • 2019-05-02
  • 2023-02-09
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多