2016-09-13 20 views
3

のフォーマットを変更する:パンダ - 私はフォーマットであるデータフレームを持つデータフレーム

level_0 level_1 counts 
0 back not_share 1183 
1 back share 1154 
2 back total 2337 
3 front not_share 697 
4 front share 1073 
5 front total 1770 
6 left not_share 4819 
7 left share 5097 
8 left total 9916 
9 other not_share 2649 
10 other share 2182 
11 other total 4831 
12 right not_share 1449 
13 right share 1744 
14 right total 3193 

私は

level_0 share not_share total 
back 1154 1183  2337 
front 1073 697  1770 

などにこのフォームを変換したい..

私は使用できる方法がありますか、それをネイティブのPythonデータ型に変換してから操作する必要がありますか?

答えて

4

使用groupbysum

df.groupby(['level_0', 'level_1']).counts.sum().unstack() 

enter image description here

+1

うーん、それは面白い(珍しい)メソッドですが! – MaxU

+1

@MaxUは小さな 'df'sのために、これはもっと速いようです。はるかに大きい(数百万行)ために、両方の方法が均等に見えます。 – piRSquared

3

あなたはpivot_table()メソッドを使用することができます

In [101]: df.pivot_table(index='level_0', columns='level_1', values='counts', aggfunc='sum') 
Out[101]: 
level_1 not_share share total 
level_0 
back   1183 1154 2337 
front   697 1073 1770 
left   4819 5097 9916 
other   2649 2182 4831 
right   1449 1744 3193 
関連する問題