Creating New Columns In Sublevel Of Multindex Pandas Columns
I have a multindex column. Higher level is some humans, sublevel is some measures. I would like to create some new columns which are derivatives of measures (eg. rolling mean).
Solution 1:
First select columns by xs
, apply rolling
and create MultiIndex
, last join
to original:
df = xf.xs('bezel', axis=1, level=1).rolling(window=2).mean()
df.columns = [df.columns, ['roll2'] * len(df.columns)]
Another solution with rename
:
df = (xf.xs('bezel', axis=1, level=1, drop_level=False).rolling(window=2).mean()
.rename(columns={'bezel':'roll2'}))
print(df)humanmikedavemattroll2roll2roll22018-01-31 NaNNaNNaN2018-02-28 0.4392970.7565300.4076062018-03-31 0.4325130.4366600.4303932018-04-30 0.2587360.4696100.8509962018-05-31 0.2788690.6988220.561285
xf=xf.join(df)print(xf)humanmikedave\measurespindragbezelspindragbezel2018-01-31 0.8110300.1145350.3265790.5977810.1940640.6597952018-02-28 0.7749710.4008880.5520160.3855390.5823510.8532662018-03-31 0.7944270.6534280.3130100.9965140.5249990.0200552018-04-30 0.3074180.1314510.2044620.0493460.1988780.9191652018-05-31 0.1963740.4215940.3532760.2440240.9309920.478479humanmattmikedave\measurespindragbezelrollroll2roll22018-01-31 0.7693080.6579630.691395NaNNaNNaN2018-02-28 0.5648840.0268640.1238180.4392970.4392970.7565302018-03-31 0.7554400.6984430.7369670.4325130.4325130.4366602018-04-30 0.7829080.9190640.9650250.2587360.2587360.4696102018-05-31 0.4140850.3397710.1575450.2788690.2788690.698822humanmattmeasureroll22018-01-31 NaN2018-02-28 0.4076062018-03-31 0.4303932018-04-30 0.8509962018-05-31 0.561285
Last if encessary sorting MultiIndex
:
xf = xf.join(df).sort_index(axis=1)
Post a Comment for "Creating New Columns In Sublevel Of Multindex Pandas Columns"