从文本中提取年龄值以在熊猫中创建新列

社交病

我有一个数据集,如下所示:

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

我想从中提取Age值,df['texts']并用它来计算new column 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年。

其他信息:“文本”列仅包含按年和月排序的“年龄”值。

欢迎任何建议。谢谢

耶斯列尔

我相信您需要:

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

#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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从 R 中的文本中提取年龄

熊猫从列中提取数字到新列中

如何根据熊猫中的列从特定行中提取文本?

从Pandas列中的元素中提取文本,并写入新列

从列中提取数字以在Pandas中创建新列

如何从熊猫列中提取特定文本

如何从熊猫的列中提取文本

熊猫从列中提取排列的对值

从Postgres中提取的列列表中为值创建数组

如何从单独的DataFrame中的匹配行值中提取列标题,并以此为基础创建新列?

数据框-在熊猫中提取URL并从中创建新列

在 R 数据框的字符列(创建新列)中提取括号之间的文本

熊猫:根据从旧数据框中的字符串中提取的数据创建新的数据框

熊猫从列值中提取子级别并填充其他列中的子级别值

熊猫:根据现有列中的值创建新列

根据另一列中的值从熊猫列中的列表中提取元素

从字符串中提取日期并保存在新的熊猫DataFrame列中

从字符串中提取字词的最后一个作为熊猫中的新列

尝试从文本字符串中提取新列的值

如何根据熊猫中的行值创建新列

根据熊猫中的行值创建新列

从列中提取文本并将其复制到新列中

从熊猫数据框groupby中提取计数之外的新列

如何从txt文档中提取文本并创建新目录?

从列中的文本中提取国家名称以创建另一列

从列中提取文本

从列中提取国家名称和年份并在数据框中创建新列

在R中创建新列-从其他列中提取常规字符

从pandas DataFrame中的文本中提取子字符串作为新列