Using Cumsum In Pandas On Group()
Solution 1:
Try this:
data2 = data1.reset_index()
data3 = data2.set_index(["Bool", "Dir", "index"]) # index is the new column created by reset_indexrunning_sum = data3.groupby(level=[0,1,2]).sum().groupby(level=[0,1]).cumsum()
The reason you cannot simply use cumsum
on data3
has to do with how your data is structured. Grouping by Bool
and Dir
and applying an aggregation function (sum
, mean
, etc) would produce a DataFrame of a smaller size than you started with, as whatever function you used would aggregate values based on your group keys. However cumsum
is not an aggreagation function. It wil return a DataFrame that is the same size as the one it's called with. So unless your input DataFrame is in a format where the output can be the same size after calling cumsum
, it will throw an error. That's why I called sum
first, which returns a DataFrame in the correct input format.
Sorry if I haven't explained this well enough. Maybe someone else could help me out?
Solution 2:
As the other answer points out, you're trying to collapse identical dates into single rows, whereas the cumsum function will return a series of the same length as the original DataFrame. Stated differently, you actually want to group by [Bool, Dir, Date], calculate a sum in each group, THEN return a cumsum on rows grouped by [Bool, Dir]. The other answer is a perfectly valid solution to your specific question, here's a one-liner variation:
data1.groupby(['Bool', 'Dir', 'Date']).sum().groupby(level=[0, 1]).cumsum()
This returns output exactly in the requested format.
For those looking for a simple cumsum on a Pandas group, you can use:
data1.groupby(['Bool', 'Dir']).apply(lambda x: x['Data'].cumsum())
The cumulative sum is calculated internal to each group. Here's what the output looks like:
BoolDirNE2000-12-30 52000-12-30 16W2001-01-02 72001-01-03 16YE2000-12-30 42001-01-03 12W2000-12-30 62000-12-30 16Name:Data,dtype:int64
Note the repeated dates, but this is doing a strict cumulative sum internal to the rows of each group identified by the Bool and Dir columns.
Post a Comment for "Using Cumsum In Pandas On Group()"