首页 > 解决方案 > 如何在python中将一串小时和分钟转换为分钟?

问题描述

我的数据框 df 中有一个列:

Time
2 hours 3 mins
5 hours 10 mins
1 hour 40 mins

我想在 df 'Minutes' 中创建一个新列,将此列转换为分钟

Minutes
123
310
100

有没有一个python函数可以做到这一点?

标签: pythonpandas

解决方案


你需要通过转换它to_datetime

s=pd.to_datetime(df.Time.replace({'hours':'hour'},regex=True),format='%H hour %M mins')
s.dt.hour*60+s.dt.minute
Out[406]: 
0    123
1    310
2    100
Name: Time, dtype: int64

或者我们使用str.findallwithnumpy dot

np.dot(np.array(df.Time.str.findall('\d+').tolist()).astype(int),[60,1])
Out[420]: array([123, 310, 100])

推荐阅读