首页 > 解决方案 > 如何将日期字符串转换为数字

问题描述

我有输入:

["3 years 8 months", "10 months", "1 year 10 months", "9 months", " 1 month ", "1 year", "3 years"]

我想要这个输出:

[3.8, 0.10, 1.10, 0.09, 0.01, 1, 3]

标签: pythonpandasreplacefindre

解决方案


您可以使用str.split

def to_num(s):
   c = {'year':1, 'years':1, 'month':0.01, 'months':0.01}
   return sum(int(s[i])*c[s[i+1]] for i in range(0, len(s), 2))

vals = ["3 years 8 months", "10 months", "1 year 10 months", "9 months", "1 month", "1 year", "3 years"]
result = [to_num(i.split()) for i in vals]

输出:

[3.08, 0.1, 1.1, 0.09, 0.01, 1, 3]

推荐阅读