0

I have some data like this:

+-----------+---------+-------+
| Duration  | Outcome | Event |
+-----------+---------+-------+
|       421 |       0 |     1 |
|       421 |       0 |     1 |
|       261 |       0 |     1 |
|        24 |       0 |     1 |
|        27 |       0 |     1 |
|       613 |       0 |     1 |
|      2454 |       0 |     1 |
|       227 |       0 |     1 |
|      2560 |       0 |     1 |
|       229 |       0 |     1 |
|      2242 |       0 |     1 |
|      6680 |       0 |     1 |
|      1172 |       0 |     1 |
|      5656 |       0 |     1 |
|      5082 |       0 |     1 |
|      7239 |       0 |     1 |
|       127 |       0 |     1 |
|       128 |       0 |     1 |
|       128 |       0 |     1 |
|      7569 |       1 |     1 |
|       324 |       0 |     2 |
|      6395 |       0 |     2 |
|      6196 |       0 |     2 |
|        31 |       0 |     2 |
|       228 |       0 |     2 |
|       274 |       0 |     2 |
|       270 |       0 |     2 |
|       275 |       0 |     2 |
|       232 |       0 |     2 |
|      7310 |       0 |     2 |
|      7644 |       1 |     2 |
|      6949 |       0 |     3 |
|      6903 |       1 |     3 |
|      6942 |       0 |     4 |
|      7031 |       1 |     4 |
+-----------+---------+-------+

Now, for each Event, with the Outcome 0/1 considered as Fail/Pass, I want to sum the total Duration of Fail/Pass events separately in 2 new columns (or 1, whatever ensures readability).

I'm new to dataframes and I feel significant logical indexing is involved here. What is the best way to approach this problem?

srkdb
  • 775
  • 3
  • 15
  • 28

2 Answers2

2

df.groupby(['Event', 'Outcome'])['Duration'].sum()

So you group by both the event then the outcome, look at the duration column then take the sum of each group.

Ben Pap
  • 2,549
  • 1
  • 8
  • 17
1

You can also try:

pd.pivot_table(index='Event', 
               columns='Outcome', 
               values='Duration', 
               data=df,
               aggfunc='sum')

which gives you a table with two columns:

+---------+-------+------+
| Outcome |   0   |  1   |
+---------+-------+------+
| Event   |       |      |
+---------+-------+------+
| 1       | 35691 | 7569 |
| 2       | 21535 | 7644 |
| 3       |  6949 | 6903 |
| 4       |  6942 | 7031 |
+---------+-------+------+
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74