Skip to content Skip to sidebar Skip to footer

Applying Function To Multi Index Pandas DataFrame

This is a sample of the DataFrame I am working on: import pandas as pd import numpy as np from scipy.stats import zscore df = pd.DataFrame( index=pd.MultiIndex.from_tuples(

Solution 1:

Use Groupby.transform:

df.groupby(level=0)['A','B','C'].transform(zscore)

#                             A         B         C
#weekdays  dates                                   
#Monday    2019-11-04  0.942314 -1.038220 -1.038401
#          2019-11-11  0.442097  1.350720  1.350641
#          2019-11-18 -1.384411 -0.312500 -0.312240
#Tuesday   2019-11-05  0.619782 -0.759579 -0.760220
#          2019-11-12  0.790974  1.412882  1.412849
#          2019-11-19 -1.410756 -0.653303 -0.652628
#Wednesday 2019-11-06  1.243122 -1.015742 -1.016228
#          2019-11-13 -0.037621  1.360045  1.359854
#          2019-11-20 -1.205501 -0.344304 -0.343626
#Thursday  2019-11-07  1.367941 -0.931907 -0.931481
#          2019-11-14 -0.994700  1.387182  1.387292
#          2019-11-21 -0.373242 -0.455275 -0.455811
#Friday    2019-11-01  1.363756 -0.759293 -0.757889
#          2019-11-08 -0.357646  1.412897  1.412967
#          2019-11-15 -1.006110 -0.653604 -0.655078
#Saturday  2019-11-02  1.414010 -1.399768 -1.399981
#          2019-11-09 -0.686236  0.525278  0.526673
#          2019-11-16 -0.727775  0.874490  0.873309
#Sunday    2019-11-03  1.412341 -1.406665 -1.406678
#          2019-11-10 -0.769170  0.576959  0.577073
#          2019-11-17 -0.643171  0.829706  0.829605

this group by level = 0 of the index (Monday,Tuesday...)

or if you want rename the index

df = df.rename_axis(index = ['weekdays','dates'])
df.groupby('weekdays').transform(zscore)

Post a Comment for "Applying Function To Multi Index Pandas DataFrame"