python - 转换 HH :MM to minutes 的 pandas 中的列

标签 python string python-3.x pandas timedelta

我想将 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/

相关文章:

python - 从 pandas 中的多索引日期获取频率表

带有空格问题的 C++ 字符串

c - 声音字符串声明挂起 Arduino 编译器

Python:如何获取字符串的索引

python - 如何将多个电子邮件添加到 "imaplib"搜索条件?

linux - 如何使在 UBUNTU 上使用 cx_Freeze 构建的 PYQT4 应用程序在 Linux SUSE 上运行。

python - 根据多个值的总和从字典中进行匹配

python - Python 中用于计算的内循环和用于保存结果的外循环

python - Ubuntu - 如何在 Python 3.3 而不是 Python 2.7 上安装 Python 模块 (BeautifulSoup)?

python - 如何在 Python 中找到字符串中的一个数字?