2

I have been thinking in a more efficient way to summarize values in a dataframe between two values.

So, I have this dataframe:

   Event   Value
   ==============
   Start   -
   Action  11
   Action  6
   Action  3
   End     -
   Start   -
   Action  8
   Action  6
   End     -

So what I want to do is sum all the values between Start and End and store the value in the initial Start

   Event    Value
   ==============
   Start   20
   Action  11
   Action  6
   Action  3
   End     -
   Start   14
   Action  8
   Action  6
   End     -

Is there a way to do this without using loops?

Thanks for your help!

2
  • initial Start as in the very start or the First Start you encounter from the End? In your case, are you talking about first start or second?
    – Deshwal
    Commented Jan 14, 2020 at 18:14
  • The idea is between a Start and End Event summarize all the actions. I am checking now the answer of @scott-boston, and will tell how it goes. Thanks :) Commented Jan 15, 2020 at 9:38

1 Answer 1

3

Try this:

df['Value'] = df['Value'].replace('-', np.nan).astype(float)

df['Value'] = (df.groupby(df['Event'].eq('Start').cumsum())['Value']
                 .transform('sum')
                 .mask(df['Event'] != 'Start', df['Value'])
                 .fillna('-'))

Output:

    Event Value
1   Start    20
2  Action    11
3  Action     6
4  Action     3
5     End     -
6   Start    14
7  Action     8
8  Action     6
9     End     -

Details:

  • Use groupby on a cumsum of events where event equals 'Start', to create groups
  • Then use transfrom to calculate sum and mask events not equal to start with the original 'Value'
  • And then use fillna to get '-' character back
2
  • I am checking it now, will tell you soon how it goes. Thanks! Commented Jan 15, 2020 at 9:39
  • 1
    Awesome this is working already, now I just notice that I need to add one more condition, having another column with an id, and only if they have the same id I need to sum them, otherwise ignore, but I am trying to solve it. Thanks for your help!! Commented Jan 15, 2020 at 12:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.