暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

pandas项目实战--年度和地区幸福指数报告

牛谈琴 2021-02-21
314

知识点总结: pandas 多列操作,包括排序、分组、pandas透视表、层级索引

根据题目的要求,通过一个案例来学习这个知识点。

排序sort_values的用法

"""
Year:从小到大
Happiness Score: 从大到小排序
"""

data_df.sort_values(['Year','Happiness Score'],ascending = [True,False],inplace = True)
data_df.to_csv(os.path.join(output_file,'sort.csv'))

  • inplace = True

如果没有这个选择,那么保存的数据并没有变化添加该选项就能看到相关数据

  • groupby

多个参数排序可以使用列表

多列分组计算

根据前文对年份地区幸福值分组求平均值。

* 每年每个地区幸福感的均值
year_region_group = data_df.groupby(by = ['Year','Region'])['Happiness Score'].mean()
print(year_region_group)

输出结果为:

Year  Region                         
2015  Australia and New Zealand          7.285000
      Central and Eastern Europe         5.332931
      Eastern Asia                       5.626167
      Latin America and Caribbean        6.144682
      Middle East and Northern Africa    5.406900
      North America                      7.273000
      Southeastern Asia                  5.317444
      Southern Asia                      4.580857
      Sub-Saharan Africa                 4.202800
      Western Europe                     6.689619
2016  Australia and New Zealand          7.323500
      Central and Eastern Europe         5.370690
      Eastern Asia                       5.624167
      Latin America and Caribbean        6.101750
      Middle East and Northern Africa    5.386053
      North America                      7.254000
      Southeastern Asia                  5.338889
      Southern Asia                      4.563286
      Sub-Saharan Africa                 4.136421
      Western Europe                     6.685667
2017  Australia and New Zealand          7.299000
      Central and Eastern Europe         5.409931
      Eastern Asia                       5.646667
      Latin America and Caribbean        5.957818
      Middle East and Northern Africa    5.369684
      North America                      7.154500
      Southeastern Asia                  5.444875
      Southern Asia                      4.628429
      Sub-Saharan Africa                 4.111949
      Western Europe                     6.703714
Name: Happiness Score, dtype: float64

透视表

pivot_table(index,columns,values,aggfunc)

  • index:透视表的行索引
  • columns:透视表的列索引
  • values: 需要统计的列数据
  • aggfunc: 聚合函数
year_region_pivot_results = pd.pivot_table(data_df,index = 'Region',columns = 'Year',values= ['Happiness Score','Economy(GDP per Capital)'],aggfunc = 'mean')

输出结果为:

Figue1

完整代码:

import os 
import pandas as pd
import matplotlib.pyplot as plt
data_file = './happiness_report.csv'
result_file = './result'
if not os.path.exists(result_file):
    os.makedirs(result_file)

def collect_data():
    data_df = pd.read_csv(data_file.sep = ',',encoding = 'utf-8')
    return data_df

def process_data(data_df):
    data_df.dropna(inplace = True)
    data_df.sort_values(['Year','Happiness Score'],inplace = True)
    return data_df

def analysis_data(data_df):
    data_group_region = data_df.groupby(by = ['Year','Region'],ascending = [True,False],inplace = True)['Happiness Score'].mean()
    data_group_pivot = pd.pivot_table(data_df,index = 'Region',columns = 'Year' values= ['Economy (GDP per Capita)','Happiness Score'],aggfunc = 'mean')
    return data_group_region,data_group_pivot
    
def save_and_show_result(data_group_region,data_group_pivot):
    data_group_region.to_csv(os.path.join(result_file,'data_group_region.csv'))
    data_group_pivot.to_csv(os.path.join(result_file,'data_group_pivot.csv'))
    
    data_group_pivot['Happiness Score'].plot(kind = 'bar',title = 'Happiness Score')
    plt.tight_layout()
    plt.show()
    
    data_group_pivot['Economy (GDP per Capita)'].plot(kind = 'bar',title = 'Economy (GDP per Capita)')
    plt.tight_layout()
    plt.show()

def main():
    data_df = collect_data
    process_data_df = process_data(data_df)
    data_group_region,data_group_pivot = analysis_data(data_df)
    save_and_show_result(data_group_region,data_group_pivot)
if __name__ == '__main__':
    main()




Economy Per Capita

(完)

文章转载自牛谈琴,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论