
[第3回] Pandasでクロス集計
jupyter notebookとpythonを利用した分析講座となっております。
Pandasを利用したクロス集計
Pandasを利用してクロス集計を試してみます。
データフレームの用意

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
クロス集計方法
商品×性別(数量)

pd.crosstab(index=df['商品'],columns=df['性別'])
(商品+価格)×性別

pd.crosstab(index=[df['商品'],df['価格']],columns=df['性別'])
商品×性別(価格合計)

pd.crosstab(index=df['商品'],columns=df['性別'],values=df['価格'],aggfunc='sum')
商品×性別(比率)

pd.crosstab(index=df['商品'],columns=df['性別'], margins=True, normalize='columns')