パンダ: ピボット テーブルの multiindex を削除する方法
pandas ピボット テーブルから multiIndex を削除するには、 reset_index()関数でvalue引数を使用できます。
p.d. pivot_table (df, index=' col1 ', columns=' col2 ', values=' col3 '). reset_index ()
次の例は、この構文を実際に使用する方法を示しています。
例: Pandas ピボットテーブルの MultiIndex を削除する
さまざまなバスケットボール選手に関する情報を含む次のパンダ データフレームがあるとします。
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], ' position ': ['G', 'G', 'F', 'F', 'G', 'F', 'F', 'F'], ' points ': [4, 4, 6, 8, 9, 5, 5, 12]}) #view DataFrame print (df) team position points 0 AG 4 1 GA 4 2 AF 6 3AF 8 4 BG 9 5 BF 5 6 BF 5 7 BF 12
ここで、チームとポジションごとの平均ポイント値を要約する次のピボット テーブルを作成するとします。
#create pivot table to summarize mean points by team and position
p.d. pivot_table (df, index=' team ', columns=' position ')
points
FG position
team
At 7.000000 4.0
B 7.333333 9.0
結果のピボット テーブルには、チームおよびポジションごとの平均ポイント値が要約されますが、multiIndex が含まれています。
multiIndex を削除するには、 pivot_table()関数のvalue引数を使用し、最後にreset_index()を追加します。
#create pivot table to summarize mean points by team and position
p.d. pivot_table (df, index=' team ', columns=' position ', values=' points '). reset_index ()
position team F G
0 to 7.000000 4.0
1 B 7.333333 9.0
結果として得られるピボット テーブルには、チームおよびポジションごとの平均ポイント値が要約されており、multiIndex は含まれなくなりました。
pivot_table()関数はデフォルトで平均値を計算することに注意してください。
合計などの別のメトリックを計算するには、次のようにaggfunc引数を使用します。
#create pivot table to summarize sum of points by team and position
p.d. pivot_table (df, index=' team ', columns=' position ', values=' points ',
aggfunc=' sum '). reset_index ()
position team FG
0 to 14 8
1 B 22 9
結果として得られるピボット テーブルには、チームおよびポジションごとのポイント値の合計が要約されており、マルチインデックスもありません。
注: pandas pivot_table()関数の完全なドキュメントはここで見つけることができます。
追加リソース
次のチュートリアルでは、パンダで他の一般的な操作を実行する方法を説明します。
パンダ: ピボット テーブルにフィルターを追加する方法
Pandas: 列の値でピボットテーブルを並べ替える方法
パンダ: ピボット テーブルに小計を追加する方法