我有一个 Pandas DataFrame,其中有一列以小时和分钟为单位的时间字符串(例如 1 小时 8 分钟)。有些单元只有几分钟(例如 47 分钟)。
我试图从这种格式转换为总分钟数的整数值(例如 1 小时 8 分钟将是 68)。
我尝试对其进行硬编码,但遇到了麻烦,因为我对 Python 还比较陌生。
有没有一个图书馆可以帮助我解决这个问题?
In [10]: df_times = pd.DataFrame(times)
df_times.columns = ["times"]
df_times
Out[10]: times
0 31 mins
1 1 hour 28 mins
2 1 hour 1 min
3 1 min
... ...
22849 ERROR
22850 7 mins
In [11]: (pd.to_timedelta(df_times["times"].str.replace('mins','min')).dt.total_seconds()//60).astype(int)
ValueError: unit abbreviation w/o a number
当我使用错误=“强制”时:
In [12]: (pd.to_timedelta(df_times["times"].str.replace('mins','min'), errors="coerce").dt.total_seconds()//60).astype(int)
ValueError: Cannot convert NA to integer
您可以使用pandas.to_timedelta() http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html and Series.dt.total_seconds() http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html方法:
In [244]: df
Out[244]:
time
0 1 hour 8 mins
1 47 mins
2 10 hours 12 minutes
3 1 min
In [245]: (pd.to_timedelta(df.time.str.replace('mins', 'min'))
...: .dt.total_seconds()//60).astype(int)
...:
Out[245]:
0 68
1 47
2 612
3 1
Name: time, dtype: int32
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)