Skip to content Skip to sidebar Skip to footer

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. T

Solution 1:

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)

Solution 2:

Assuming Time Stamp is of datetime dtype:

df.groupby(pd.Grouper(key='Time Stamp', freq='W')) \
  .apply(lambda x: x.to_csv(r"/path/to/{}W{}.csv".format(x.name.year,x.name.week)))

Post a Comment for "How To Partition Pandas Data Frame Based On Week And Save As CSV?"