27 分析電子游戲在各國的銷量并使用堆疊柱狀圖呈現(xiàn)

分析電子游戲在各國的銷量并使用堆疊柱狀圖呈現(xiàn)

目標(biāo)
i業(yè)務(wù)場景
數(shù)據(jù)清洗過濾
堆疊柱狀圖

數(shù)據(jù)集的樣式

pandas 數(shù)據(jù)源下載地址

數(shù)據(jù)集的樣式: 名稱、平臺摊唇、

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)  #這是二維數(shù)組
    return data_df
def inspect_data(data_df):
    #數(shù)據(jù)有噪聲的時候,讀取為保險起見,會被讀取成obj類型
    print(f'數(shù)據(jù)一共有{data_df.shape[0]}行, {data_df.shape[1]}列')
    print('-----------------------------------------------------')
    print('數(shù)據(jù)預(yù)覽:')
    # 如果想看又怕太多掖举,可以用data_df.head()包券,只顯示前幾行
    print(data_df.head())
    print('-----------------------------------------------------')
    print('數(shù)據(jù)的基本信息:')
    # data_df.info()可以看數(shù)據(jù)類型,字符串看成obj類型株旷,數(shù)字會自動讀取成float或int
    print(data_df.info())
    print('-----------------------------------------------------')
    print('數(shù)據(jù)統(tǒng)計信息')
    #均值再登、最大值、最小值啥的
    print(data_df.describe())
    print('-----------------------------------------------------')
def process_data(data_df):
    #數(shù)據(jù)處理
    #處理空值
    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一下晾剖,新的數(shù)據(jù)和原數(shù)據(jù)斷開關(guān)聯(lián)性锉矢,否則這是深拷貝

    #全球銷量 像加字典一樣就行了,多加一列齿尽,全都是向量化操作
    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'原始數(shù)據(jù)有{data_df.shape[0]}記錄沈撞,處理后的數(shù)據(jù)有{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的數(shù)據(jù)
    filtered_data_df = data_df[data_df['Global_Sales'] >5]

    # 在四個市場中分別對發(fā)行商進行求和
    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')   #直接畫缠俺,無需重復(fù)調(diào)用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():
    #數(shù)據(jù)獲取
    data_df = collect_data()

    #查看數(shù)據(jù)信息
    inspect_data(data_df)

    #數(shù)據(jù)處理
    proc_data_df = process_data(data_df)

    #數(shù)據(jù)分析
    top20_games, sales_cmp_results = analyze_data(proc_data_df)

    #結(jié)果展示
    save_and_show_results(top20_games, sales_cmp_results)

if __name__ == '__main__':
    main()

運行結(jié)果

數(shù)據(jù)一共有16598行, 9列
-----------------------------------------------------
數(shù)據(jù)預(yù)覽:
                       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]
-----------------------------------------------------
數(shù)據(jù)的基本信息:
<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
-----------------------------------------------------
數(shù)據(jù)統(tǒng)計信息
               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]
-----------------------------------------------------
原始數(shù)據(jù)有16598記錄,處理后的數(shù)據(jù)有10行記錄

top20

銷量比較

總結(jié)

總結(jié)

練習(xí)

使用堆疊柱狀圖比較不同來源的 PM2.5數(shù)值差異

  • 題目描述:
  1. 添加一列diff用于比較中國環(huán)保部和美國使館檢測的PM2.5值的差異(兩列數(shù)據(jù)的絕對值差)
  2. 找出差別最大的10天的記錄
  3. 使用分組柱狀圖比較中國環(huán)保部和美國使館檢測的每年平均PM2.5的值
  • 題目要求:

  • 使用Pandas進行數(shù)據(jù)分析及可視化

  • 數(shù)據(jù)文件:

  • 數(shù)據(jù)源下載地址:https://video.mugglecode.com/Beijing_PM.csv (數(shù)據(jù)源與上節(jié)課相同)

  • Beijing_PM.csv贷岸,包含了2013-2015年北京每小時的PM2.5值壹士。每行記錄為1小時的數(shù)據(jù)。

  • 共7列數(shù)據(jù)偿警,分別表示:

  1. year: 年躏救,2013-2015
  2. month: 月,1-12
  3. day: 日,1-31
  4. hour: 小時盒使,0-23
  5. season:季度崩掘,1-4
  6. PM_China: 中國環(huán)保部檢測的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()  #讀取數(shù)據(jù)

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('看看操作完的數(shù)據(jù)集\n',data_diff.describe())

for i in range(10):
    item = data_diff.iloc[i, :]      #逐行取出,這個零行就是數(shù)據(jù)少办,標(biāo)簽有但是不占行
    print('中美測出的第{}大數(shù)據(jù)差值苞慢,是在{}年{}月{}日{(diào)}時,差值為{}'.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()

運行結(jié)果

看看操作完的數(shù)據(jù)集
               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大數(shù)據(jù)差值英妓,是在2015年4月15日19時挽放,差值為579.0
中美測出的第2大數(shù)據(jù)差值,是在2013年8月8日14時蔓纠,差值為469.0
中美測出的第3大數(shù)據(jù)差值辑畦,是在2014年4月17日1時,差值為453.0
中美測出的第4大數(shù)據(jù)差值腿倚,是在2013年8月14日12時纯出,差值為442.0
中美測出的第5大數(shù)據(jù)差值,是在2013年12月4日12時敷燎,差值為432.0
中美測出的第6大數(shù)據(jù)差值潦刃,是在2014年4月9日19時,差值為358.0
中美測出的第7大數(shù)據(jù)差值懈叹,是在2014年4月13日13時乖杠,差值為350.0
中美測出的第8大數(shù)據(jù)差值,是在2013年8月11日8時澄成,差值為325.0
中美測出的第9大數(shù)據(jù)差值胧洒,是在2014年4月21日9時,差值為301.0
中美測出的第10大數(shù)據(jù)差值墨状,是在2013年3月18日2時卫漫,差值為299.0

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市肾砂,隨后出現(xiàn)的幾起案子列赎,更是在濱河造成了極大的恐慌,老刑警劉巖镐确,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件包吝,死亡現(xiàn)場離奇詭異,居然都是意外死亡源葫,警方通過查閱死者的電腦和手機诗越,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來息堂,“玉大人嚷狞,你說我怎么就攤上這事块促。” “怎么了床未?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵竭翠,是天一觀的道長。 經(jīng)常有香客問我薇搁,道長斋扰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任只酥,我火速辦了婚禮,結(jié)果婚禮上呀狼,老公的妹妹穿的比我還像新娘裂允。我一直安慰自己,他們只是感情好哥艇,可當(dāng)我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布绝编。 她就那樣靜靜地躺著,像睡著了一般貌踏。 火紅的嫁衣襯著肌膚如雪十饥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天祖乳,我揣著相機與錄音逗堵,去河邊找鬼。 笑死眷昆,一個胖子當(dāng)著我的面吹牛蜒秤,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播亚斋,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼作媚,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了帅刊?” 一聲冷哼從身側(cè)響起纸泡,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎赖瞒,沒想到半個月后女揭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡栏饮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年田绑,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抡爹。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡掩驱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情欧穴,我是刑警寧澤民逼,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站涮帘,受9級特大地震影響拼苍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜调缨,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一疮鲫、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧弦叶,春花似錦俊犯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至立莉,卻和暖如春绢彤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蜓耻。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工茫舶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人刹淌。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓奇适,卻偏偏與公主長得像,于是被迫代替她去往敵國和親芦鳍。 傳聞我的和親對象是個殘疾皇子嚷往,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容