我一直在寻找解决方案,最近的解决方案是在这里: Convert time string expressed as <number>[m|h|d|s|w] to seconds in Python
但是,所有解决方案都不起作用,因为时间格式有时仅包含一个单位,并且在整个列中不一致。例如
['4h 30m 24s', '13w 5d', '11w']
当我在整个列中.apply()
失败时,它将失败。如何将所有这些行转换为秒?我尝试过df['time_value'].str.split()
,但这是一种非常混乱且看似效率低下的方法,必须有更好的方法吗?
答案 0 :(得分:3)
apply
采用这种方法怎么样?
def convert_to_seconds(s):
seconds = 0
seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
for part in s.split():
number = int(part[:-1])
unit = part[-1]
seconds += number * seconds_per_unit[unit]
return seconds
答案 1 :(得分:0)
您可以先使用stack
然后将map
映射到第二个
s=pd.Series(l)
s=s.str.split(expand=True).stack().to_frame('ALL')
s['v']=s['ALL'].str[:-1].astype(int)
s['t']=s['ALL'].str[-1]
seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
(s.t.map(seconds_per_unit)*s.v).unstack()
Out[625]:
0 1 2
0 14400.0 1800.0 24.0
1 7862400.0 432000.0 NaN
2 6652800.0 NaN NaN