I've been searching for a solution to this and the closest I got was here: Convert time string expressed as <number>[m|h|d|s|w] to seconds in Python
however none of the solutions work because the time format only sometimes contains one unit and is inconsistant throughout the column. e.g.
['4h 30m 24s', '13w 5d', '11w']
when I .apply()
this over the entire column it fails. How can I convert all of these rows into seconds? I tried df['time_value'].str.split()
but this is a very messy and seemingly inefficient way to do this, there must be a better way?
How about apply
ing this method?
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加