Pergunta

I have a DataFrame like following.

1   A  B  D     E  None
2   B  C  E  None  None
3   A  B  D     E  None
4   A  B  C     E  None
5   A  B  C     D     E

I want to count each item in the DataFrame. How to do it?

B(6), E(5), A(4), C(4), D(4) etc.
Foi útil?

Solução

stack it first and then use value_counts:

import pandas as pd
from StringIO import StringIO

data = \
"""A,B,D,E,None
B,C,E,None,None
A,B,D,E,None
A,B,C,E,None
A,B,C,D,E"""

# Creation of the dataframe
df = pd.read_csv(StringIO(data),sep = ',',header=None)
# Perform the magic operation (stack and value_counts) on the dataframe
res = df.stack().value_counts()

The result looks like:

E       5
B       5
None    5
A       4
C       3
D       3
dtype: int64

This question has already been asked on StackOverflow

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top