Reputation: 1985
I'm new to Python and a little confused on how to do something that is likely trivial.
I have a Pandas dataframe with a column containing time in seconds.
DF
ID Call_Duration
1 127
2 153
3 23
4 87
5 96
I'd like to display that as a new column showing time in minutes and seconds: MM:SS
ID Call_Duration Minutes
1 127 02:07
2 153 02:33
3 23 00:23
4 87 01:27
5 96 01:36
I've tried using to_timedelta in pandas but it displays much more than I want (shows precision to days):
DF['Minutes'] = DF.to_timedelta(DF['Call_Duration'],unit="m")
I also found a function that would work for a single entry but not sure how to adapt it to work for a dataframe column instead of throwing it in a loop.
def format_duration(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
Upvotes: 2
Views: 1030
Reputation: 1579
Try using your format_duration
, with dataframe.apply, specifying axis=1:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html
import pandas as pd
frame = pd.read_csv('test.csv')
print(frame)
def format_duration(row):
seconds = row.Call_Duration ## changed this
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
frame['duration'] = frame.apply(format_duration, axis=1)
## now frame has a new column with the desired results
print(frame)
ID Call_Duration duration
0 1 127 00:02:07
1 2 153 00:02:33
2 3 23 00:00:23
3 4 87 00:01:27
4 5 96 00:01:36
edit: I added some comments in the inline code. That should answer it- please let me know if not! thx
Upvotes: 2
Reputation: 76
To convert seconds to minutes and seconds:
def separate(seconds):
'''This functions separates seconds into a (minutes, seconds) tuple.'''
return (
floor(seconds / 60), # devide by 60 and remove remainder
remain = seconds % 60 # take away 60 until less than 60 (modulo)
)
Upvotes: -1