Reputation: 2024
I am using the timedelta function from datetime package to convert seconds into hours and minutes format.
Here's an example:
secs = timedelta(seconds = 30)
print(secs)
00:00:30
When is run this on a pandas column that I need to convert, I run into the unsupported type error. It looks like this happens when it the function encounters a '0' and is not sure how to handle it, I think.
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
I am wondering why it isn't able to convert seconds = 0 to 00:00:00. Here's my code:
for i, row in EmpComm.iterrows():
val = timedelta(seconds = EmpComm['Duration (secs)'].iloc[i])
EmpComm['Duration (hh:mm)'][i] = val
Upvotes: 2
Views: 6983
Reputation: 862661
Dont use loops with iterrows
, because exist vectorized solution.
You need to_timedelta
with parameter 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
Upvotes: 4