對比Excel,學習pandas數(shù)據(jù)透視表

導讀:更簡單了呢~

01 Excel中做數(shù)據(jù)透視表





02 pandas用pivot_table()做數(shù)據(jù)透視表
pd.pivot_table(data,index=None,columns=None,
values=None,aggfunc='mean',
margins=False,margins_name='All',
dropna=True,fill_value=None)
data 相當于Excel中的"選中數(shù)據(jù)源"; index 相當于上述"數(shù)據(jù)透視表字段"中的行; columns 相當于上述"數(shù)據(jù)透視表字段"中的列; values 相當于上述"數(shù)據(jù)透視表字段"中的值; aggfunc 相當于上述"結(jié)果"中的計算類型; margins 相當于上述"結(jié)果"中的總計; margins_name 相當于修改"總計"名,為其它名稱。
dropna 表示是否刪除缺失值,如果為True時,則把一整行全作為缺失值刪除; fill_value 表示將缺失值,用某個指定值填充。
03 案例說明

df = pd.read_excel(r"C:\Users\黃偉\Desktop\pivot_table.xlsx")
display(df.sample(5))
df.insert(1,"月份",df["銷售日期"].apply(lambda x:x.month))
display(df.sample(5))
df1 = pd.pivot_table(df,index="品牌",columns="月份",
values="銷售數(shù)量",aggfunc=np.sum)
display(df1)

df = pd.read_excel(r"C:\Users\黃偉\Desktop\pivot_table.xlsx")
display(df.sample(5))
df.insert(1,"月份",df["銷售日期"].apply(lambda x:x.month))
display(df.sample(5))
df1 = pd.pivot_table(df,index="品牌",columns=["銷售區(qū)域","月份"],
values="銷售數(shù)量",aggfunc=np.sum)
display(df1)

df = pd.read_excel(r"C:\Users\黃偉\Desktop\pivot_table.xlsx")
display(df.sample(5))
df.insert(1,"月份",df["銷售日期"].apply(lambda x:x.month))
display(df.sample(5))
df1 = pd.pivot_table(df,index=["品牌","銷售區(qū)域"],columns="月份",
values="銷售數(shù)量",aggfunc=np.sum)
display(df1)

df = pd.read_excel(r"C:\Users\黃偉\Desktop\pivot_table.xlsx")
display(df.sample(5))
df.insert(1,"月份",df["銷售日期"].apply(lambda x:x.month))
display(df.sample(5))
df1 = pd.pivot_table(df,index="品牌",columns="月份",
values=["銷售數(shù)量","貨號"],
aggfunc={"銷售數(shù)量":"sum","貨號":"count"},
margins=True,margins_name="總計")
display(df1)


評論
圖片
表情
