How to count the frequency of the elements in a dataframe's row?

Viewed 139

I have data frame like below

df = pd.DataFrame([['pqr', 'abc', 'pqr', 'NULL', 'NULL']], 
                  columns=['col1', 'col2', 'col3', 'col4', 'col5'])

  col1 col2 col3  col4  col5
0  pqr  abc  pqr  NULL  NULL

Desired output:

code count
pqr   2
abc   1

How can I do to get above in Python?

I have tried with groupby:

df.groupby(['col1', 'col2', 'col3', 'col4', 'col5']).count().reset_index()

I didn't get desired output.

3 Answers

To get the occurences over the dataframe -

df.loc[0:(length(df.index)-1)].stack().to_frame()[0].value_counts()

To get occurences over any row i -

df.loc[i].value_counts()

Use value_counts and drop NULL.

import pandas as pd

df = pd.DataFrame([['pqr', 'abc', 'pqr', 'NULL', 'NULL']],
                  columns=['col1', 'col2', 'col3', 'col4', 'col5'])

counts = df.T.value_counts()
counts.index.rename('code', inplace=True)
counts.sort_index(inplace=True)  # avoids warning by pandas about dropping from unsorted index
counts = counts.drop('NULL')
counts = pd.DataFrame(counts, columns=['count'])

print(counts)

out:

      count
code       
pqr       2
abc       1

Given your df:

>>> df

  col1 col2 col3  col4  col5
0  pqr  abc  pqr   NaN   NaN

You can use stack() and value_counts():

df.stack().value_counts().reset_index().\
    rename({'index':'code',
            0:'count'},axis=1)

Prints:

  code  count
0  pqr      2
1  abc      1
Related