1

I have a dataframe with below structure,

| Date       |   Item | Location | Event   |
|------------|-------:|----------|---------|
| 01-06-2019 | Item_1 | Loc_1    | Event_1 |
| 01-06-2019 | Item_1 | Loc_1    | Event_1 |
| 02-06-2019 | Item_1 | Loc_1    | Event_1 |
| 02-06-2019 | Item_1 | Loc_1    | Event_2 |
| 02-06-2019 | Item_1 | Loc_2    | Event_2 |
| 02-06-2019 | Item_2 | Loc_1    | Event_3 |
| 03-06-2019 | Item_2 | Loc_1    | Event_3 |
| 03-06-2019 | Item_2 | Loc_1    | Event_3 |

I want to count the number of events occurred with reference to Item + Location in a day. Result as below,

| Date       |   Item | Location | Event_1 | Event_2 | Event_3 |
|------------|-------:|----------|---------|---------|---------|
| 01-06-2019 | Item_1 | Loc_1    | 2       | 0       | 0       |
| 02-06-2019 | Item_1 | Loc_1    | 1       | 1       | 0       |
| 02-06-2019 | Item_1 | Loc_2    | 0       | 1       | 0       |
| 02-06-2019 | Item_2 | Loc_1    | 0       | 0       | 1       |
| 03-06-2019 | Item_2 | Loc_1    | 0       | 0       | 2       |

Tried pandas pivot_table, could not get the result I want.

Thanks!

1 Answer 1

6

Use crosstab with DataFrame.reset_index:

df1 = pd.crosstab([df['Date'], df['Item'], df['Location']], df['Event']).reset_index()
print (df1)
Event        Date    Item Location  Event_1  Event_2  Event_3
0      01-06-2019  Item_1    Loc_1        2        0        0
1      02-06-2019  Item_1    Loc_1        1        1        0
2      02-06-2019  Item_1    Loc_2        0        1        0
3      02-06-2019  Item_2    Loc_1        0        0        1
4      03-06-2019  Item_2    Loc_1        0        0        2

Alternative solution:

df1=df.groupby(['Date','Item','Location','Event']).size().unstack(level = -1,fill_value=0).reset_index()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.