【pandas】根据dataframe某一列的值求另外一列的均值,然后将结果转换成键值对

情景:计算两次考试,所有学生的平均成绩:

 

'''a.csv
date,name,grade
2020-07-01,mary,70
2020-07-01,tom,80
2020-07-01,jerry,70
2020-07-02,mary,80
2020-07-02,tom,90
2020-07-02,tom,100'''

grade = pd.read_csv('C:\\test\\a.csv')

# average grade at 0701 and 0702
avg = grade['grade'].groupby(grade['date']).mean()

# format grade avg to 'avg: XX'
import math
avg_new = avg.apply(lambda x: 'avg: '+str(math.floor(x))) 

# last step, change avg_new to key-value
avg_new.to_dict()

结果:

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页