pandasのDataFrameの機能の一つであるpivot_table()関数は、データフレームを二次元の表形式に集計するための便利な関数です。この関数を使用すると、データフレームを行と列に分割し、行と列の両方で集計を行うことができます。
pivot_table()関数は、以下のような引数を受け取ります。
- data:集計するデータフレーム
- index:行になるキー
- columns:列になるキー
- values:集計する値
- aggfunc:集計関数
例えば、以下のようなデータフレームを持っているとします。
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two'],
'C': ['small', 'large', 'large', 'small', 'small', 'large', 'small', 'small', 'large'],
'D': [1, 2, 2, 3, 3, 4, 5, 6, 7],
'E': [2, 4, 5, 5, 6, 6, 8, 9, 9]
})
print(df)
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
このデータフレームを、AとBを行、Cを列にして、Dの平均値を集計するには、以下のようにpivot_table()関数を使用します。
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two'],
'C': ['small', 'large', 'large', 'small', 'small', 'large', 'small', 'small', 'large'],
'D': [1, 2, 2, 3, 3, 4, 5, 6, 7],
'E': [2, 4, 5, 5, 6, 6, 8, 9, 9]
})
print(df.pivot_table(index=['A', 'B'], columns='C', values='D', aggfunc='mean'))
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 2.0 1.0
two NaN 3.0
このように、pivot_table()関数を使用することで、データフレームを行と列に分割し、行と列の両方で集計を行うことができます。