2

Supposing that I have a DataFrame along the lines of:

David Maxime
0 cat duck
1 dog cat
2 horse duck
3 cat dog

How to obtain the following result ?

Animals Total
cat 3
duck 2
dog 2
horse 1

I found many codes but not for the case where a result is return according to number of occurrences of datas in unique column.

0

2 Answers 2

2

You can use

pd.concat([df.David.value_counts(), df.Maxine.value_counts()], axis=1).fillna(0).sum(axis=1)

This creates a dataframe with the value counts along each column, then sums the rows.

Sign up to request clarification or add additional context in comments.

Comments

0

One option is to melt the dataframe, and use value_counts:

(df.melt(value_name = 'Animal')
   .value_counts(subset='Animal')
   .reset_index(name='Total')
)
  Animal  Total
0    cat      3
1    dog      2
2   duck      2
3  horse      1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.