2016-05-03 10 views
2

Wenn ich einen Datenrahmen wie dieses:Ausbrechen Spalte von Gruppen in Pandas

type value group 
    a  10  one 
    b  45  one 
    a  224  two 
    b  119  two 
    a  33 three 
    b  44 three 

wie ich es in diese machen:

type  one  two three 
    a  10  224  33 
    b  45  119  44 

Ich dachte, es pivot_table sein würde, aber das gibt mir nur eine neu gruppierte Liste.

Antwort

2

Ich glaube, Sie brauchen pivot mit rename_axis (neu in pandas0.18.0) und reset_index:

print df.pivot(index='type', columns='group', values='value') 
     .rename_axis(None, axis=1) 
     .reset_index() 

    type one three two 
0 a 10  33 224 
1 b 45  44 119 

Wenn Reihenfolge der Spalten ist wichtig:

df = df.pivot(index='type', columns='group', values='value').rename_axis(None, axis=1) 

print df[['one','two','three']].reset_index() 
    type one two three 
0 a 10 224  33 
1 b 45 119  44 

EDIT:

In Ihrem realen Daten, die Sie erhalten können, Fehler:

print df.pivot(index='type', columns='group', values='value') 
     .rename_axis(None, axis=1) 
     .reset_index() 

ValueError: Index contains duplicate entries, cannot reshape

print df 
    type value group 
0 a  10 one 
1 a  20 one 
2 b  45 one 
3 a 224 two 
4 b 119 two 
5 a  33 three 
6 b  44 three 

Problem ist in der zweiten Reihe - Sie Indexwert erhalten a und Spalte one zwei Werte - 10 und 20. Funktion pivot_table aggregieren Daten in diesem Fall. Die Standard-Aggregatfunktion ist np.mean, aber Sie können sie durch Parameter aggfunc:

print df.pivot_table(index='type', columns='group', values='value', aggfunc=np.mean) 
     .rename_axis(None, axis=1) 
     .reset_index() 

    type one three two 
0 a 15  33 224 
1 b 45  44 119 

print df.pivot_table(index='type', columns='group', values='value', aggfunc='first') 
     .rename_axis(None, axis=1) 
     .reset_index() 

    type one three two 
0 a 10  33 224 
1 b 45  44 119 

print df.pivot_table(index='type', columns='group', values='value', aggfunc=sum) 
     .rename_axis(None, axis=1) 
     .reset_index() 

    type one three two 
0 a 30  33 224 
1 b 45  44 119 
ändern