简体   繁体   中英

Find average using dictionary key

I have these columns in my dataframe:

数据框

I need to find average of all the [Count] values where Day is 1 or 2 and so on.

I've tried that by using key dictionary:

col_dict = dict(zip(df6.Day, df6.Count))

k=2  # Enter Day
#print(k)
for keys in col_dict.keys():
    if keys == k:
        for i in col_dict:
            a=col_dict[keys] where col_dict==k

But I think this code is not correct.

Pandas has purpose-built methods for grouping and aggregating data. Here you can use groupby + mean :

res = df6.groupby('Day')['Count'].mean()

There is no need for dictionary conversion or explicit iteration when vectorised operations are available. If you need a dictionary result, you can convert in a separate step:

res_dict = res.to_dict()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM