Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partition pandas data frame based on week and save as 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

My expected output is:

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

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.

like image 249
User1 Avatar asked Oct 24 '25 10:10

User1


1 Answers

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

Last loop groupby and call to_csv:

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)
like image 178
jezrael Avatar answered Oct 26 '25 23:10

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!