分析電子游戲在各國的銷量并使用堆疊柱狀圖呈現(xiàn)
目標(biāo)
i業(yè)務(wù)場景
數(shù)據(jù)清洗過濾
堆疊柱狀圖
數(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ù)值差異
- 題目描述:
- 添加一列diff用于比較中國環(huán)保部和美國使館檢測的PM2.5值的差異(兩列數(shù)據(jù)的絕對值差)
- 找出差別最大的10天的記錄
- 使用分組柱狀圖比較中國環(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ù)偿警,分別表示:
- year: 年躏救,2013-2015
- month: 月,1-12
- day: 日,1-31
- hour: 小時盒使,0-23
- season:季度崩掘,1-4
- PM_China: 中國環(huán)保部檢測的PM2.5值
- 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