我是Python的新手,对如何做一些可能微不足道的事情感到有些困惑。
我有一个Pandas数据框,其中的列包含以秒为单位的时间。
DF
ID Call_Duration
1 127
2 153
3 23
4 87
5 96
我希望将其显示为以分钟和秒为单位显示时间的新列: 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
我已尝试在熊猫中使用to_timedelta,但它显示的内容比我想要的要多得多(显示精确到天数):
DF['Minutes'] = DF.to_timedelta(DF['Call_Duration'],unit="m")
我还发现了一个适用于单个条目但不确定如何使其适用于数据帧列而不是将其放入循环中的函数。
def format_duration(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
答案 0 :(得分:1)
尝试使用带有dataframe.apply的format_duration
,指定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
编辑:我在内联代码中添加了一些注释。应该回答 - 如果没有,请告诉我! THX
答案 1 :(得分:-1)
将秒转换为分钟和秒:
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)
)