Ich habe einen Datenrahmen:elegante Art und Weise in einen Multi-Level-Pandas Datenrahmen iterieren
import numpy as np import pandas as pd
a = pd.DataFrame(np.random.rand(10,6)) cols = [['A', 'B', 'C'],
['AA','BB']] a.columns = pd.MultiIndex.from_product(
cols,
names= ['first lvl', 'second level'])
, die einen Multiindex gibt df nach unten:
first lvl A B C
second level AA BB AA BB AA BB
0 0.991608 0.469706 0.338347 0.254777 0.739046 0.980094
1 0.039133 0.959985 0.718216 0.746632 0.341260 0.264836
2 0.164068 0.158672 0.175882 0.211732 0.146807 0.678957
3 0.324433 0.343780 0.269040 0.432309 0.469457 0.247455
4 0.932380 0.314262 0.439924 0.037954 0.641936 0.011523
5 0.608288 0.308212 0.680107 0.988747 0.349255 0.775298
6 0.082478 0.859175 0.546415 0.471169 0.013312 0.824054
7 0.244569 0.049261 0.194941 0.350334 0.203621 0.408066
8 0.132751 0.092825 0.237527 0.383277 0.288257 0.764209
9 0.417155 0.578300 0.325731 0.504903 0.718891 0.861813
ich für Iterierte durch Spalt mag A, B und C und tun ein np.polyfit(AA, BB, deg=1)
.
Gibt es eine elegante und einfache Möglichkeit, andere zu tun, als mit:
cols = np.unique(a.columns.get_level_values(0)) beta =
[np.polyfit(a[col]['AA'], a[col]['BB'], deg= 1) for col in cols]