How to create a dataframe with number of row having value above of zero for specifics columns?

Viewed 35

I have a dataframe like this

name  skill_1  skill_2
john  2        0
james 0        1

I would like to have a count of the rows above of zero for each columns starting with "skill".

Expected output for the new dataframe:

skills   count
skill_1  1   
skill_2  1

How can I do it with Pandas ?

2 Answers

You can try:

df.filter(like="skill").gt(0).sum(axis=0).to_frame("count")
  • filter for the columns that include "skill"
  • Mark those entries that are greater than 0 as True and others as False
  • Sum row-wise (axis=0) where True will be treated as 1 and False 0 to get the counts
  • Convert to dataframe

to get

         count
skill_1      1
skill_2      1

Just filter by the condition on the "skill" columns:

import pandas as pd

df = pd.DataFrame(columns=['name','skill_1','skill_2'],
                  data=[['john',2,0],
                   ['james',0,1]])

skill_cols = [x for x in df.columns if 'skill' in x]

subset_df = df[df[skill_cols] > 0][skill_cols]
column_count = subset_df.count()
Related