2

I would like to loop through a pandas dataframe's columns using a for loop to count the value based on the list given.

My_list =[ 'apple', 'orange', 'grapes' ]

I can do it with value_count() functions as given below to calculate frequency

df['Fruits']. value_count() 

but I want to calculate using the for loop to iterate over dataframe to get count and average of the list given.

My_list =[ 'apple', 'orange', 'grapes' ] 

Df:   
    Fruits  value
    apple      10
    apple      20 
    orange      2
    grapes      5 
    grapes     10 
    grapes      3

My output should be like this.

Fruits    count    average
apple      2         15 
orange     1          2 
grapes     3          6

1 Answer 1

2

Use:


My_list = ['apple', 'orange', 'grapes'] 
df1 = (df.query("Fruits in @My_list")
         .groupby('Fruits', sort=False)['value']
         .agg(['size','mean'])
         .rename(columns={'mean':'average', 'size':'count'})
         .reset_index())

df1 = (df[df['Fruits'].isin(My_list)]
        .groupby('Fruits', sort=False)['value']
        .agg(['size','mean'])
        .rename(columns={'mean':'average', 'size':'count'})
        .reset_index())

print (df1)
   Fruits  count  average
0   apple      2       15
1  orange      1        2
2  grapes      3        6

If want use loop, it should be slowier:

L = []
for x in My_list:
    s = df.loc[df['Fruits'] == x, 'value']
    #print (s)
    L.append({'Fruits': x, 'average':s.mean(), 'count':len(s)})

df = pd.DataFrame(L, columns=['Fruits','count','average'])
print (df)
   Fruits  count  average
0   apple      2     15.0
1  orange      1      2.0
2  grapes      3      6.0
Sign up to request clarification or add additional context in comments.

2 Comments

I add also loop solution, but faster/ better is use groupby + agg solution.
Great. Thanks for listing the different options

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.