0

I want to count the frequency of a value that are same in 2 column, also adding a column at the end that display the counting number & delete the first cloumn.

The dataframe I have

| Column A | Column B | Column C |
| -------- | -------- | -------- |
| Column A | Cat      | Fish     |
| Column A | Cat      | Apple    |
| Column A | Cat      | Apple    |
| Column A | Dog      | Lemon    |
| Column A | Dog      | Fish     |
| Column A | Dog      | Fish     |

The expected outcome is like

| Column A | Column B | Column C | 
| -------- | -------- | -------- | 
| Cat      | Fish     |     1    |
| Cat      | Apple    |     2    |
| Dog      | Lemon    |     1    |
| Dog      | Fish     |     2    |

I have tried the

df['Column B'].value_counts()

But I don't know to handle 2 cloumn at the same time.

1 Answer 1

1

You can use GroupBy.count :

out = (
        df.groupby(["Column B", "Column C"],
                   as_index=False, sort=False)
        ["Column A"].count()
       )

# Output :

print(out)
     Column B    Column C  Column A
0   Cat         Fish              1
1   Cat         Apple             2
2   Dog         Lemon             1
3   Dog         Fish              2
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.