1
$\begingroup$

Consider a pandas dataframe where each index is represented as a datetime object in the form like 2009-01-30 23:01:45 .

In order to calculate the total value of a column in each day, I've used the following workarounds:

df['col1'].resample('D').sum().cumsum()

or

df.groupby(df.index.date)['col1'].sum().cumsum()

where both can return my desired output.

However I was wondering is there another solution without using two successive aggregation functions, .sum().cumsum() ?

$\endgroup$

1 Answer 1

1
$\begingroup$

Both sum() and cumsum() will do different operations.
sum() with groupby will add all the Values in the Val column for each date. whereas cumsum() - cumulative sum will add the first date(row) sum result with the second date(row) sum result and populate in the second row and add this value with the third date(row) sum result and it continues.

So it is based in the requirement whether you need just sum of values for each date or you need cumulative sum as well. Thanks

$\endgroup$
2
  • $\begingroup$ Thank you for your answer. But I seek another solution to replace such operations. $\endgroup$
    – sci9
    Nov 14, 2021 at 16:42
  • $\begingroup$ I think both are different operations so you can't replace both as one. $\endgroup$ Nov 22, 2021 at 13:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.