Home > Net >  value counts not working with a column filter in Pandas
value counts not working with a column filter in Pandas

Time:10-30

everyone I was trying to count the number of Yes answered in a column depending on the answer from another previous column to generate pie charts so I'm having problems with this because is giving me counts in boolean like in image below, (This is my codeline):

answers = ['Yes']
hello = (df['Are you okay?']== 'No') &(df['Are yu sad?'].isin(answers))

enter image description here

Actually I just want that the result will be something like this:

Yes 
110

CodePudding user response:

hello in this case, is an array of boolean. Apply the array to original dataframe.

answers = ['Yes']
hello = df[(df['Are you okay?']== 'No') &(df['Are yu sad?'].isin(answers))]

then apply hello.value_counts()

CodePudding user response:

If need count values of boolean mask use sum for processing Trues:

answers = ['Yes']
hello = (df['Are you okay?']== 'No') &(df['Are yu sad?'].isin(answers))

df = pd.DataFrame({answers[0]: hello.sum()})

If ned count Are yu sad? column by condition df['Are you okay?']== 'No' use:

df1 = (df.loc[df['Are you okay?']== 'No', 'Are yu sad?']
         .value_counts()
         .rename_axis('Vals')
         .reset_index(name='Count'))
  • Related