This is the dataframe I've got:
data = {'Year' : [2021, 2021, 2021, 2022, 2022, 2022],
'Class':['A', 'A', 'B', 'A', 'C', 'C'],
'Animal':['dog|cat|bird', 'cat|dog', 'tiger|dog', 'cat|bird', 'dog|cat|rabbit', 'rabbit|dog|tiger',]}
df = pd.DataFrame(data)
So the df looks like:
| Year | Class | Animal |
|---|---|---|
| 2021 | A | dog|cat|bird |
| 2021 | A | cat|dog |
| 2021 | B | tiger|dog |
| 2022 | A | cat|bird |
| 2022 | C | dog|cat|rabbit |
| 2022 | C | rabbit|dog|tiger |
What I'd like to do is to calculate the number of each animal in each year and class. For example, I want to get the following dataframe:
| Year | Class | Animal | Count |
|---|---|---|---|
| 2021 | A | dog | 2 |
| 2021 | A | cat | 2 |
| 2021 | A | bird | 1 |
| 2021 | B | tiger | 1 |
| 2021 | B | dog | 1 |
| 2022 | A | cat | 1 |
| 2022 | A | bird | 1 |
| 2022 | C | dog | 2 |
| 2022 | C | cat | 1 |
| 2022 | C | rabbit | 2 |
| 2022 | C | tiger | 1 |
Does anyone have any suggestions about achieving this? I'd be really appreciate it.