2016-05-11 9 views
2

Angesichts dieser Datenrahmen und Pivot-Tabelle:Pandas Pivot-Tabelle Nested Sortierung Teil 2

import pandas as pd 
df=pd.DataFrame({'A':['x','y','z','x','y','z'], 
       'B':['one','one','one','two','two','two'], 
       'C':[7,5,3,4,1,6]}) 
df 


    A B  C 
0 x one  7 
1 y one  5 
2 z one  3 
3 x two  4 
4 y two  1 
5 z two  6 

table = pd.pivot_table(df, index=['A', 'B'],aggfunc=np.sum) 

table 
A B 
x one 7 
    two 4 
y one 5 
    two 1 
z one 3 
    two 6 
Name: C, dtype: int64 

Ich möchte solche die Pivot-Tabelle sortieren, dass die Werte absteigend in ‚C‘ sortiert werden.

So:

A B 
x one 7 
    two 4 
y one 5 
    two 1 
z two 6 
    one 3 

Vielen Dank im Voraus!

+1

Haben Sie in 'C' bedeuten absteigend? – piRSquared

+0

Ja, tut mir leid. Die Frage wurde korrigiert. –

Antwort

1

Dies sollte funktionieren

df.groupby(['A'])['B', 'C'].apply(lambda x: x.set_index('B').sort_values('C', ascending=0)) 
+0

Ich lache darüber wie gut das ist, wenn das überhaupt Sinn macht. Vielen Dank! –

+0

@ DanceParty2 Nein, es macht keinen Sinn und das bringt mich auch zum Lachen. – piRSquared

1

versuchen Sie dies:

In [12]: pd.pivot_table(df, index=['A', 'B'],aggfunc='sum').reset_index().sort_values(by=['A','C'], ascending=[1,0]) 
Out[12]: 
    A B C 
0 x one 7 
1 x two 4 
2 y one 5 
3 y two 1 
5 z two 6 
4 z one 3