Pandas Datenrahmen:Pandas Spalte Multiindex Subtrahierend Spalten voneinander
Constructor:
c = pd.MultiIndex.from_product([['AAPL','AMZN'],['price','custom']])
i = pd.date_range(start='2017-01-01',end='2017-01-6')
df1 = pd.DataFrame(index=i,columns=c)
df1.loc[:,('AAPL','price')] = list(range(51,57))
df1.loc[:,('AMZN','price')] = list(range(101,107))
df1.loc[:,('AAPL','custom')] = list(range(1,7))
df1.loc[:,('AMZN','custom')] = list(range(17,23))
df1.index.set_names('Dates',inplace=True)
df1.sort_index(axis=1,level=0,inplace=True) # needed for pd.IndexSlice[]
df1
Produziert: (kann nicht herausfinden, wie die Ausgabe von Jupyter Notebook-Format)
AAPL AMZN
custom price custom price
Dates
2017-01-01 1 51 17 101
2017-01-02 2 52 18 102
2017-01-03 3 53 19 103
2017-01-04 4 54 20 104
2017-01-05 5 55 21 105
2017-01-06 6 56 22 106
Frage: Wie kann ich eine 3. Spalte an der 2. le erstellen vel des MultiIndex das ist der Unterschied zwischen price
und custom
? Dies sollte getrennt für jede oberste Spaltenebene berechnet werden, d. H. Getrennt für AAPL und AMZN.
Versuchte Lösungen:
versuchte ich pd.IndexSlice
auf 2 Arten verwendet wird, beide geben mir alle NaNs
:
df1.loc[:,pd.IndexSlice[:,'price']].sub(df1.loc[:,pd.IndexSlice[:,'custom']])
df1.loc[:,pd.IndexSlice[:,'price']] - df1.loc[:,pd.IndexSlice[:,'custom']]
Returns:
AAPL AMZN
custom price custom price
Dates
2017-01-01 NaN NaN NaN NaN
2017-01-02 NaN NaN NaN NaN
2017-01-03 NaN NaN NaN NaN
2017-01-04 NaN NaN NaN NaN
2017-01-05 NaN NaN NaN NaN
2017-01-06 NaN NaN NaN NaN
Wie kann ich eine dritte Spalte hinzufügen mit dem Unterschied?
Danke.
Ausgezeichnet danke! –
@JoshD Kein Problem. Die Spalten wurden auch hier zum Original hinzugefügt. –