0

I have a pandas dataframe that contains data that looks like this:

levels char_1 char_2
a      dog    dog
a      cat    dog
b      cow    cat
b      dog    dog

I'd like to group_by the levels column and compute the total number of times that a value appears either in the char_1 column or char_2 column

The resulting dataframe would look like:

levels char  count
a      dog    3
a      cat    1
b      dog    2
b      cow    1
b      cat    1

I've experimented with pivot tables, but can't wrap my head around pandas syntax.

1 Answer 1

4

Use DataFrame.melt for unpivot and then GroupBy.size for counts:

df1 = (df.melt('levels', value_name='char')
         .groupby(['levels','char'])
         .size()
         .reset_index(name='count'))
print (df1)
  levels char  count
0      a  cat      1
1      a  dog      3
2      b  cat      1
3      b  cow      1
4      b  dog      2
Sign up to request clarification or add additional context in comments.

1 Comment

Shockingly fast answer. Of course! The answer is always melt. Thank you.

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.