【Python/Pandas】ピボットテーブル化と逆変換

pandas ver0.22

pd.pivotでピボットテーブルを作成。
pd.meltで逆の変換ができる。
コード全体は下記のとおり。

import pandas as pd
df_pivot = pd.DataFrame([[101, 201, 301],
                         [102, 202, 302],
                         [103, 203, 303]], columns=['a', 'b', 'c'], index=['a', 'b', 'c'])
df_melted = df_pivot.reset_index().melt(id_vars=['index'])
df_pivoted = df_melted.pivot(index='index', columns='variable', values='value')


まず元のデータフレームdf_pivotがこれ。 f:id:gushigo:20180528225700p:plain

これをmeltを使って変形。

df_melted = df_pivot.reset_index().melt(id_vars=['index'])

f:id:gushigo:20180528225657p:plain

これをpivotで元の形に戻せる。

df_pivoted = df_melted.pivot(index='index', columns='variable', values='value')

f:id:gushigo:20180528225705p:plain

逆ピボットテーブルの変換は、Tidy data(整然データ)化と呼べると思う。

pd.pivot()はデータの重複がないことを前提としている。
重複があると下記のようなエラーメッセージが出る。

ValueError: Index contains duplicate entries, cannot reshape

こういうときはpd.drop_duplicatess()で重複を削除するか、pd.pivot_tableを使うようにしましょう。