我有一个数据集,如下所示:
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] 删除。
我来说两句