我有一个数据集如下:
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年。
其他信息:文字列仅包含年龄和月份的年龄值。
欢迎任何建议。感谢
答案 0 :(得分:2)
我相信你需要:
注意:如果没有年份和月份文本,那么解决方案会计入多年
#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