27 分析电子游戏在各国的销量并使用堆叠柱状图呈现

2018-07-26  本文已影响69人  夏威夷的芒果

分析电子游戏在各国的销量并使用堆叠柱状图呈现

目标 i业务场景 数据清洗过滤 堆叠柱状图

数据集的样式

pandas 数据源下载地址

数据集的样式: 名称、平台、
import matplotlib.pyplot as plt
import pandas as pd
import os

#比较销量

file_path = '/Users/miraco/PycharmProjects/DataMining/data_pd/video_games_sales.csv'
outpath = './coffee_stat/ouptput'

#os.mkdir 與 os.makedirs 的差別在於 os.makedirs 會遞迴地去建立目錄,也就是說連同中繼的目錄也會一起建立
if not os.path.exists(outpath):
    os.makedirs(outpath)

def collect_data():
    data_df = pd.read_csv(file_path)  #这是二维数组
    return data_df
def inspect_data(data_df):
    #数据有噪声的时候,读取为保险起见,会被读取成obj类型
    print(f'数据一共有{data_df.shape[0]}行, {data_df.shape[1]}列')
    print('-----------------------------------------------------')
    print('数据预览:')
    # 如果想看又怕太多,可以用data_df.head(),只显示前几行
    print(data_df.head())
    print('-----------------------------------------------------')
    print('数据的基本信息:')
    # data_df.info()可以看数据类型,字符串看成obj类型,数字会自动读取成float或int
    print(data_df.info())
    print('-----------------------------------------------------')
    print('数据统计信息')
    #均值、最大值、最小值啥的
    print(data_df.describe())
    print('-----------------------------------------------------')
def process_data(data_df):
    #数据处理
    #处理空值
    cln_data_df = data_df.dropna()
    #按年份过滤
    cond = (cln_data_df['Year'] >= 2005) & (cln_data_df['Year'] <= 2017)
    filtered_data_df  = cln_data_df[cond].copy()  #copy一下,新的数据和原数据断开关联性,否则这是深拷贝

    #全球销量 像加字典一样就行了,多加一列,全都是向量化操作
    filtered_data_df['Global_Sales'] = filtered_data_df['NA_Sales'] + filtered_data_df['EU_Sales'] + filtered_data_df['JP_Sales'] + filtered_data_df['Other_Sales']
    print(f'原始数据有{data_df.shape[0]}记录,处理后的数据有{filtered_data_df.shape[1]}行记录')
    return filtered_data_df


def analyze_data(data_df):
    # 取全球销量前20进行查看
    top20_games = data_df.sort_values(by = 'Global_Sales', ascending = False).head(20)

    # 全球销量大于500W的数据
    filtered_data_df = data_df[data_df['Global_Sales'] >5]

    # 在四个市场中分别对发行商进行求和
    sales_cmp_results = filtered_data_df.groupby('Publisher')[['NA_Sales', 'EU_Sales', 'JP_Sales', 'Other_Sales']].sum()

    return top20_games, sales_cmp_results



def save_and_show_results(top20_games, sales_cmp_results):
    top20_games.to_csv(os.path.join(outpath,'top20_games.csv'), index = False)#保存时候去掉索引,因为pandas 保存时候是默认带有索引的
    sales_cmp_results.to_csv(os.path.join(outpath, 'sales_cmp_results.csv'))  #这个分组操作不带索引,没事

    top20_games.plot(kind = 'bar', x = 'Name', y = 'Global_Sales')   #直接画,无需重复调用figure
    plt.title('Top20 Game sales (2005 - 2017)')
    plt.tight_layout()
    plt.savefig(os.path.join(outpath, 'top20_games.png'))
    plt.show()

    sales_cmp_results.plot.bar(stacked = True)   #堆叠柱状图
    plt.title('Game sales Comparison(2005 - 2017)')
    plt.tight_layout()
    plt.savefig(os.path.join(outpath, 'sales_cmp_results.png'))
    plt.show()

def main():
    #数据获取
    data_df = collect_data()

    #查看数据信息
    inspect_data(data_df)

    #数据处理
    proc_data_df = process_data(data_df)

    #数据分析
    top20_games, sales_cmp_results = analyze_data(proc_data_df)

    #结果展示
    save_and_show_results(top20_games, sales_cmp_results)

if __name__ == '__main__':
    main()

运行结果

数据一共有16598行, 9列
-----------------------------------------------------
数据预览:
                       Name Platform     ...      JP_Sales Other_Sales
0                Wii Sports      Wii     ...          3.77        8.46
1         Super Mario Bros.      NES     ...          6.81        0.77
2            Mario Kart Wii      Wii     ...          3.79        3.31
3         Wii Sports Resort      Wii     ...          3.28        2.96
4  Pokemon Red/Pokemon Blue       GB     ...         10.22        1.00

[5 rows x 9 columns]
-----------------------------------------------------
数据的基本信息:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 16598 entries, 0 to 16597
Data columns (total 9 columns):
Name           16598 non-null object
Platform       16598 non-null object
Year           16327 non-null float64
Genre          16598 non-null object
Publisher      16540 non-null object
NA_Sales       16598 non-null float64
EU_Sales       16598 non-null float64
JP_Sales       16598 non-null float64
Other_Sales    16598 non-null float64
dtypes: float64(5), object(4)
memory usage: 1.1+ MB
None
-----------------------------------------------------
数据统计信息
               Year      NA_Sales      ...           JP_Sales   Other_Sales
count  16327.000000  16598.000000      ...       16598.000000  16598.000000
mean    2006.406443      0.264667      ...           0.077782      0.048063
std        5.828981      0.816683      ...           0.309291      0.188588
min     1980.000000      0.000000      ...           0.000000      0.000000
25%     2003.000000      0.000000      ...           0.000000      0.000000
50%     2007.000000      0.080000      ...           0.000000      0.010000
75%     2010.000000      0.240000      ...           0.040000      0.040000
max     2020.000000     41.490000      ...          10.220000     10.570000

[8 rows x 5 columns]
-----------------------------------------------------
原始数据有16598记录,处理后的数据有10行记录

top20
销量比较

总结

总结

练习

使用堆叠柱状图比较不同来源的 PM2.5数值差异

  1. 添加一列diff用于比较中国环保部和美国使馆检测的PM2.5值的差异(两列数据的绝对值差)
  2. 找出差别最大的10天的记录
  3. 使用分组柱状图比较中国环保部和美国使馆检测的每年平均PM2.5的值
  1. year: 年,2013-2015
  2. month: 月,1-12
  3. day: 日,1-31
  4. hour: 小时,0-23
  5. season:季度,1-4
  6. PM_China: 中国环保部检测的PM2.5值
  7. PM_US: 美国使馆检测的PM2.5值

答案

import os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
filepath = '/Users/miraco/PycharmProjects/DataMining/data_pd/Beijing_PM.csv'
outpath = '/Users/miraco/PycharmProjects/DataMining/coffee_stat/ouptput'

data = pd.read_csv(filepath).dropna()
data_db = data.copy()  #读取数据

data_db['diff'] = abs(data_db['PM_China'] - data_db['PM_US'])  #添加差值列
data_diff = data_db.sort_values(by = 'diff', ascending = False).head(10)    #找出差别最大的10天的记录
print('看看操作完的数据集\n',data_diff.describe())

for i in range(10):
    item = data_diff.iloc[i, :]      #逐行取出,这个零行就是数据,标签有但是不占行
    print('中美测出的第{}大数据差值,是在{}年{}月{}日{}时,差值为{}'.format(
        i+1,
        int(item['year']),
        int(item['month']),
        int(item['day']),
        int(item['hour']),
        item['diff']
    ))

year_mean = data.copy().groupby('year')['PM_China','PM_US'].mean()
year_mean.plot(kind = 'bar', stacked = False, width = 0.35)
plt.xticks(np.arange(4), rotation = 0)

plt.title = ['Year mean PM 2.5 statistics from PRC and US']
plt.legend(['by China', 'by US' ],loc = 'best')
plt.tight_layout()
plt.show()

运行结果

看看操作完的数据集
               year      month     ...           PM_US        diff
count    10.000000  10.000000     ...       10.000000   10.000000
mean   2013.600000   5.900000     ...      199.100000  400.800000
std       0.699206   2.923088     ...      245.649909   89.618698
min    2013.000000   3.000000     ...       31.000000  299.000000
25%    2013.000000   4.000000     ...       47.500000  331.250000
50%    2013.500000   4.000000     ...       90.000000  395.000000
75%    2014.000000   8.000000     ...      171.750000  450.250000
max    2015.000000  12.000000     ...      722.000000  579.000000

[8 rows x 8 columns]
中美测出的第1大数据差值,是在2015年4月15日19时,差值为579.0
中美测出的第2大数据差值,是在2013年8月8日14时,差值为469.0
中美测出的第3大数据差值,是在2014年4月17日1时,差值为453.0
中美测出的第4大数据差值,是在2013年8月14日12时,差值为442.0
中美测出的第5大数据差值,是在2013年12月4日12时,差值为432.0
中美测出的第6大数据差值,是在2014年4月9日19时,差值为358.0
中美测出的第7大数据差值,是在2014年4月13日13时,差值为350.0
中美测出的第8大数据差值,是在2013年8月11日8时,差值为325.0
中美测出的第9大数据差值,是在2014年4月21日9时,差值为301.0
中美测出的第10大数据差值,是在2013年3月18日2时,差值为299.0

image.png
上一篇 下一篇

猜你喜欢

热点阅读