ピボット

Sort pandas df into individual columns – StackOverflow

欲しい形を得る為に,grouperを作成して,ピボットテーブルを得る.

import pandas as pd
import numpy as np


df = pd.DataFrame(
    {
        'A' : [10,20,30,40,40,30,20,10,5,10,15,20,20,15,10,5],
        'B' : ['X','X','X','X','Y','Y','Y','Y','X','X','X','X','Y','Y','Y','Y'],
        'C' : ['W','W','Z','Z','Z','Z','W','W','W','W','Z','Z','Z','Z','W','W'],                                         
    }
)

print(df, end='\n\n')

df['gcol'] = df['B'].add(df['C'])
idx = np.unique(df['gcol'].values, return_index=True)[1].max() + 2
arr = np.repeat(np.arange(1, len(df)//idx+1), idx)
df['key'] = arr
df['gcol'] = df['gcol'].add(df['key'].map(str))
df['grow'] = df.groupby(['gcol', 'key']).cumcount()

res = df.pivot(index='grow', columns='gcol', values='A')

print(res)
     A  B  C
0   10  X  W
1   20  X  W
2   30  X  Z
3   40  X  Z
4   40  Y  Z
5   30  Y  Z
6   20  Y  W
7   10  Y  W
8    5  X  W
9   10  X  W
10  15  X  Z
11  20  X  Z
12  20  Y  Z
13  15  Y  Z
14  10  Y  W
15   5  Y  W

gcol  XW1  XW2  XZ1  XZ2  YW1  YW2  YZ1  YZ2
grow                                        
0      10    5   30   15   20   10   40   20
1      20   10   40   20   10    5   30   15
カテゴリー: 未分類 パーマリンク