python - Pandas Column Multiindex Subtracting Columns from each other -
pandas dataframe:
constructor:
c = pd.multiindex.from_product([['aapl','amzn'],['price','custom']]) = 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 pd.indexslice[] df1 produces: (can't figure out how format output jupyter notebook)
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 question: how can create 3rd column @ 2nd level of multiindex difference between price , custom? should calculated separately each top column level, i.e. separately aapl , amzn.
attempted solutions:
i tried using pd.indexslice in 2 ways, both give me 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 how can add third column difference?
thanks.
you might consider subtraction of values:
df1.loc[:, pd.indexslice[:, 'price']] - df1.loc[:,pd.indexslice[:,'custom']].values to join back, can use pd.concat:
in [221]: df2 = (df1.loc[:, pd.indexslice[:, 'price']] - df1.loc[:,pd.indexslice[:,'custom']].values)\ .rename(columns={'price' : 'new'}) in [222]: pd.concat([df1, df2], axis=1) out[222]: aapl amzn aapl amzn custom price custom price new new dates 2017-01-01 1 51 17 101 50 84 2017-01-02 2 52 18 102 50 84 2017-01-03 3 53 19 103 50 84 2017-01-04 4 54 20 104 50 84 2017-01-05 5 55 21 105 50 84 2017-01-06 6 56 22 106 50 84
Comments
Post a Comment