Sha*_*110 5 python time-series pandas
我在Pandas中有一个Dataframe,它在几分钟内给出了一个名为“ duration”的列。
我想获得一个新列,该列以小时:分钟(HH:MM)给出持续时间。
I\xe2\x80\x99m 对 Pandas 不熟悉,但从分钟到分钟和小时的转换的一般方法如下所示:
\n\ntotal_minutes = 374\n\n# Get hours with floor division\nhours = total_minutes // 60\n\n# Get additional minutes with modulus\nminutes = total_minutes % 60\n\n# Create time as a string\ntime_string = "{}:{}".format(hours, minutes)\n\nprint(time_string) # Prints \'6:14\' in this example\nRun Code Online (Sandbox Code Playgroud)\n\n您还可以使用以下方法避免中间步骤divmod():
time_string = "{}:{}".format(*divmod(total_minutes, 60))\nRun Code Online (Sandbox Code Playgroud)\n\n在这里,*允许format()接受作为两个单独参数返回的元组(包含两个整数)divmod()。
假设您的 DataFrame 如下所示:
df = pd.DataFrame({'duration': [20, 10, 80, 120, 30, 190]})
Run Code Online (Sandbox Code Playgroud)
使用pd.to_datetime具有strftime:
pd.to_datetime(df.duration, unit='m').dt.strftime('%H:%M')
0 00:20
1 00:10
2 01:20
3 02:00
4 00:30
5 03:10
dtype: object
Run Code Online (Sandbox Code Playgroud)
小智 6
最好像这样使用:
minutes = 204
print("%02d:%02d" % (divmod(minutes, 60)))
Run Code Online (Sandbox Code Playgroud)
这将产生格式良好的输出 03:24。