如何根据周划分 pandas 数据框并另存为CSV? [英] How to partition pandas data frame based on week and save as CSV?

查看:68
本文介绍了如何根据周划分 pandas 数据框并另存为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,如下所示.这个数据帧大约一个月的时间.如何根据周划分此数据帧?我需要将每4周另存为4个CSV文件.

I have a pandas data frame as below. This data frame about one month period. How do I partition this data frame based on week? I need save each 4 weeks as seperate 4 CSV files.

Time Stamp              Id  Latitude    Longitude
01/10/2016 15:22:51:700 1      23        50
01/10/2016 16:28:08:026 1      23        50
01/10/2016 16:28:09:026 1      12        45
02/10/2016 19:00:08:026 2      23        50
02/10/2016 20:28:08:026 1      23        50
03/10/2016 19:00:08:000 2      23        50
03/10/2016 01:02:33:123 2      23        50
03/10/2016 06:15:08:500 1      23        50
03/10/2016 10:01:07:022 3      28        88
......
......
31/10/2016 13:09:17:044 1      33        80

我的预期输出是:

Time Stamp              Id  Latitude    Longitude
01/10/2016 15:22:51:700 1      23        50
01/10/2016 16:28:08:026 1      23        50
01/10/2016 16:28:09:026 1      12        45
02/10/2016 19:00:08:026 2      23        50
02/10/2016 20:28:08:026 1      23        50
03/10/2016 19:00:08:000 2      23        50
03/10/2016 01:02:33:123 2      23        50
03/10/2016 06:15:08:500 1      23        50
03/10/2016 10:01:07:022 3      28        88
......
......
07/10/2016 03:09:10:066 5      28        78

这应该是我的第一周.接下来的几周是从08/10/2016至14/10/2017,从15/10/2016至21/10/2017和从22/10/2016至31/10/2017.

This should be my first week. Next weeks from 08/10/2016 to 14/10/2017, from 15/10/2016 to 21/10/2017 and from 22/10/2016 to 31/10/2017.

推荐答案

您可以通过datetimes,然后转换为year-weekofyear -docs/stable/generated/pandas.Series.dt.strftime.html"rel =" nofollow noreferrer> strftime .

You can convert column first to datetimes and then to year-weekofyear by strftime.

最后一个循环groupby并调用 :

ts = pd.to_datetime(df['Time Stamp'], format='%d/%m/%Y %H:%M:%S:%f').dt.strftime('%Y-%W')

for i, x in df.groupby(ts):
   x.to_csv('{}.csv'.format(i), index=False)

这篇关于如何根据周划分 pandas 数据框并另存为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆