电竞比分网-中国电竞赛事及体育赛事平台

分享

Python數(shù)據(jù)分析之聚合與透視表

 F2967527 2020-08-19

◆ ◆ ◆  ◆ 


嚴小樣兒原創(chuàng)第N篇~

讀取數(shù)據(jù)

Python用于數(shù)據(jù)分析好不好,因人而異。
但是,excel能做的Python也能做。比如聚合,透視表。我認為更簡單一下。
如果大家在工作中用得到數(shù)據(jù)庫,用得到Python,可以學習一下數(shù)據(jù)透視表。

第一步:讀取數(shù)據(jù)
import pymysqlimport pandas as pdimport matplotlib.pyplot as plt
# 建立連接conn = pymysql.connect('localhost','username','password','database')
# 讀取SQL為dfsql = 'select * from table'df = pd.read_sql(sql,con=conn)

數(shù)據(jù)聚合

第二步:數(shù)據(jù)聚合

# 查看基本屬性print(df.index)print(df.columns)print(df.info())
# 修改時間格式df['stat_month'] = pd.to_datetime(df['stat_month'],format='%Y%m')
# 設(shè)置索引df.set_index('stat_month',inplace = True)print(df.head())
# 只看一個月份的df_grp1601= df['20160101'].groupby(['brand','areaname'],as_index = False)['profit'].sum()print(df_grp1601)
df_grpbrand = df_grp1601.groupby('brand').sum()print(df_grpbrand[df_grpbrand>200000].plot(kind = 'bar'))


數(shù)據(jù)透視表


第三步:數(shù)據(jù)透視表
pd.pivot_table(df['20160101':'20161201'],values = 'profit',\               index = ['stat_month','brand'],\               columns ='areaname',aggfunc='sum' )

祝大家早日富可敵國!

記得

在看

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多