Sie benötigen bestehende Indexebene Foo
, stapeln Sie die gewünschte Spalte ‚Coo‘, unstack und dann die Indexebene neu anordnen. Nachdem Sie Ihre Indexstufen getauscht haben, möchten Sie sie wahrscheinlich sortieren. Zum Schluss möchten Sie vielleicht den Spaltennamen aller Werte löschen (val
).
df = (pd.DataFrame({'Foo': [124, 124, 134, 134] * 2,
'Bar': [1, 2, 1, 2] * 2,
'Coo': ['BAZ'] * 4 + ['PAL'] * 4,
'val': list('ACEGBDFH')})
.set_index(['Foo', 'Bar', 'Coo'])
.unstack('Coo'))
>>> df
val
Coo BAZ PAL
Foo Bar
124 1 A B
2 C D
134 1 E F
2 G H
df = df.unstack('Foo').stack('Coo')
df.index = df.index.swaplevel(0, 1)
>>> df
val
Foo 124 134
Coo Bar
BAZ 1 A E
PAL 1 B F
BAZ 2 C G
PAL 2 D H
df.sort_index(inplace=True)
>>> df
val
Foo 124 134
Coo Bar
BAZ 1 A E
2 C G
PAL 1 B F
2 D H
df.columns = df.columns.droplevel()
>>> df
Foo 124 134
Coo Bar
BAZ 1 A E
2 C G
PAL 1 B F
2 D H
Danke. Es hat total funktioniert. –
Ich bin froh, Ihnen helfen zu können. – Alexander