如何使用for循环遍历pandas数据帧列,以根据给定的列表计算值

时间:2018-01-15 12:30:30

标签: python python-3.x pandas

我想使用for循环遍历pandas dataframe的列,根据给定的列表计算值。

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

我可以使用下面给出的value_count()函数来计算频率

df['Fruits']. value_count() 

但是我想使用for循环来计算迭代数据帧以获得给定列表的计数和平均值。

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

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

我的输出应该是这样的。

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

1 个答案:

答案 0 :(得分:1)

使用:

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

如果想要使用循环,它应该更慢:

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