timedelta秒组件的不受支持的类型:numpy.int64

时间:2018-10-10 05:28:57

标签: python pandas datetime timedelta

我正在使用timedelta function的datetime包将秒转换为小时和分钟格式。

这里是一个示例:

secs = timedelta(seconds = 30)
print(secs)

00:00:30 

在需要转换的pandas列上运行此命令时,遇到了不受支持的类型错误。我认为,当函数遇到“ 0”并且不确定如何处理时,似乎会发生这种情况。

EmpComm = pd.DataFrame({
         'Duration (secs)':[3488, 2994,0, 0],
         'Duration (hh:mm)':['0:58:08','0:49:54',np.nan,np.nan],

})
print (EmpComm)
   Duration (secs) Duration (hh:mm)
0             3488          0:58:08
1             2994          0:49:54
2                0              NaN
3                0              NaN

Data sample

我想知道为什么它不能将秒= 0转换为00:00:00。这是我的代码:

for i, row in EmpComm.iterrows():

    val = timedelta(seconds = EmpComm['Duration (secs)'].iloc[i])
    EmpComm['Duration (hh:mm)'][i] = val

1 个答案:

答案 0 :(得分:1)

Dont use loops with iterrows,因为存在矢量化解决方案。

您需要to_timedelta和参数unit

EmpComm = pd.DataFrame({
         'Duration (secs)':[3488, 2994,0, 0],
         'Duration (hh:mm)':['0:58:08','0:49:54',np.nan,np.nan],

})

EmpComm['Duration (hh:mm)'] = pd.to_timedelta(EmpComm['Duration (secs)'], unit='s')
print (EmpComm)
   Duration (secs) Duration (hh:mm)
0             3488         00:58:08
1             2994         00:49:54
2                0         00:00:00
3                0         00:00:00