Ich glaube, Sie brauchen pivot
mit rename_axis
(neu in pandas
0.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