Ich möchte einen Pandas DataFrame, der von einer Pivot-Tabelle abgeleitet ist, in eine Reihendarstellung konvertieren, wie unten gezeigt. DieseFlachen DataFrame mit Multi-Index-Spalten
ist, wo ich bin:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'goods': ['a', 'a', 'b', 'b', 'b'],
'stock': [5, 10, 30, 40, 10],
'category': ['c1', 'c2', 'c1', 'c2', 'c1'],
'date': pd.to_datetime(['2014-01-01', '2014-02-01', '2014-01-06', '2014-02-09', '2014-03-09'])
})
# we don't care about year in this example
df['month'] = df['date'].map(lambda x: x.month)
piv = df.pivot_table(["stock"], "month", ["goods", "category"], aggfunc="sum")
piv = piv.reindex(np.arange(piv.index[0], piv.index[-1] + 1))
piv = piv.ffill(axis=0)
piv = piv.fillna(0)
print piv
die
stock
goods a b
category c1 c2 c1 c2
month
1 5 0 30 0
2 5 10 30 40
3 5 10 10 40
in Ergebnisse und das ist, wo ich bekommen möchten.
goods category month stock
a c1 1 5
a c1 2 0
a c1 3 0
a c2 1 0
a c2 2 10
a c2 3 0
b c1 1 30
b c1 2 0
b c1 3 10
b c2 1 0
b c2 2 40
b c2 3 0
Previously, benutzen ich
piv = piv.stack()
piv = piv.reset_index()
print piv
loszuwerden, das Multi-Indizes zu erhalten, aber dies führt zu dem, weil ich jetzt auf zwei Säulen schwenkte (["goods", "category"]
):
month category stock
goods a b
0 1 c1 5 30
1 1 c2 0 0
2 2 c1 5 30
3 2 c2 10 40
4 3 c1 5 10
5 3 c2 10 40
Weiß jemand, wie ich den Multi-Index in der Spalte loswerden kann und das Ergebnis in einen DataFrame des exemplarischen Formats bringen kann?
hmmmm, schmelzen (mein Antwort) verliert Monat aus dem Index :( –
Danke. Es funktioniert gut mit meinem Beispiel. Allerdings verstehe ich nicht ganz, warum die Verwendung von 'Stack' zuvor funktioniert und ich sollte jetzt 'Entstapeln' verwenden. – orange