我想将 hh:mm 格式的数据集中的列转换为分钟。我尝试了以下代码,但它显示“AttributeError: 'Series' object has no attribute 'split'”。数据采用以下格式。我在数据集中也有 nan 值,计划是计算值的中值,然后用中值填充具有 nan 的行
02:32
02:14
02:31
02:15
02:28
02:15
02:22
02:16
02:22
02:14
我已经试过了
s = dataset['Enroute_time_(hh mm)']
hours, minutes = s.split(':')
int(hours) * 60 + int(minutes)
最佳答案
我建议您避免按行计算。您可以对 Pandas/NumPy 使用矢量化方法:
df = pd.DataFrame({'time': ['02:32', '02:14', '02:31', '02:15', '02:28', '02:15',
'02:22', '02:16', '02:22', '02:14', np.nan]})
values = df['time'].fillna('00:00').str.split(':', expand=True).astype(int)
factors = np.array([60, 1])
df['mins'] = (values * factors).sum(1)
print(df)
time mins
0 02:32 152
1 02:14 134
2 02:31 151
3 02:15 135
4 02:28 148
5 02:15 135
6 02:22 142
7 02:16 136
8 02:22 142
9 02:14 134
10 NaN 0
关于python - 转换 HH :MM to minutes 的 pandas 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53098627/