Skip to content Skip to sidebar Skip to footer

Pandas Dataframe Splitted Into Weeks

I have problems reshaping a dataframe into weeks, such that I'm able to look at one particular week easy, but also aggregated week-days together, i.e. Monday + Monday, Tuesday + Tu

Solution 1:

I'm not entirely sure what your objective is here, but you should definitely consider using groupby rather than for loops (which will be much faster).

You can groupby the week (from the DatetimeIndex):

In [1]: rng = pd.date_range('2013', freq='D', periods=10)

In [2]: df = pd.DataFrame(np.random.randn(10), rng)

In [3]: df.index.week
Out[3]: array([32, 32, 32, 33, 33, 33, 33, 33, 33, 33], dtype=int32)

In [4]: df.groupby(df.index.week).sum()
Out[4]:
           0323.600673330.791545

Similarly, you can groupby day (of the week):

In [5]: df.groupby(df.index.dayofweek).sum()
Out[5]:
          001.26830710.38732221.4169483 -0.38084441.46406850.03096560.205453

or more complicated arrays derived from these...

I think you'll be able to apply a different function here (rather than sum) to achieve the desired result.

Post a Comment for "Pandas Dataframe Splitted Into Weeks"