![見出し画像](https://assets.st-note.com/production/uploads/images/66839340/rectangle_large_type_2_17d2b825a2bb0234ed9ceb314e1df938.png?width=1200)
[第3回] Pandasでクロス集計
jupyter notebookとpythonを利用した分析講座となっております。
Pandasを利用したクロス集計
Pandasを利用してクロス集計を試してみます。
データフレームの用意
![画像1](https://assets.st-note.com/production/uploads/images/66326653/picture_pc_7061e65918425812a35d25231cf4b50d.png?width=1200)
import numpy as np
import pandas as pd
sex = np.random.choice(['男性','女性'],size=10)
item = np.random.choice(['お皿', 'ナイフ', 'フォーク'],size=10)
price = np.random.choice([100,1000,5000],size=10)
df = pd.DataFrame({'性別':sex,'商品':item,'価格':price})
df
クロス集計方法
商品×性別(数量)
![画像2](https://assets.st-note.com/production/uploads/images/66326773/picture_pc_dbcbab2217fba9e23cd0c37e20b5d93a.png?width=1200)
pd.crosstab(index=df['商品'],columns=df['性別'])
(商品+価格)×性別
![画像3](https://assets.st-note.com/production/uploads/images/66326841/picture_pc_0093d7e7df967658b533a8ae0f022045.png?width=1200)
pd.crosstab(index=[df['商品'],df['価格']],columns=df['性別'])
商品×性別(価格合計)
![画像4](https://assets.st-note.com/production/uploads/images/66326971/picture_pc_7a3a62ce375fa2670cd176c3c9aa3ccd.png?width=1200)
pd.crosstab(index=df['商品'],columns=df['性別'],values=df['価格'],aggfunc='sum')
商品×性別(比率)
![画像5](https://assets.st-note.com/production/uploads/images/66327051/picture_pc_b1c2026404e896141be64868fea0aa70.png?width=1200)
pd.crosstab(index=df['商品'],columns=df['性別'], margins=True, normalize='columns')
次回講座
この記事が気に入ったらサポートをしてみませんか?