2017-06-28 7 views

Antwort

1

I gelöst dies durch bodytype von columns zu index durch eine andere pivot_table Erstellen, Verschieben und dann einfach geteilt wird.

pivot_df["my_metric"] = pivot_df["heart_rate"]/pivot_df["blood_pressure"]

+1

Sie haben wirklich nicht Ihre eigene Frage beantworten. Du hast ein anderes Format präsentiert, weil es einfacher für dich war. Zuallererst können Sie den Job mit 'pivot_df.unstack ('bodytype') 'abschließen. Zweitens würde ich sagen, dass es eine schlechte Form ist, eine Frage zu stellen, ohne die Daten bereitzustellen, die zum Generieren der Pivot-Tabelle benötigt werden, und dann eine Lösung anzubieten, die von den Daten abhängt, die Sie nicht angegeben haben. Wie hilft das anderen? – piRSquared

2

Eine bessere Lösung kann gefunden werden, wenn Sie ein Beispiel für Daten-Pivot bereitstellen.

hr = df.heart_rate 
bp = df.blood_pressure 

keys = ['heart_rate', 'blood_pressure', 'my_metric'] 
pd.concat([hr, bp, hr/bp], axis=1, keys=keys) 

Beispiel

idx = pd.MultiIndex.from_product([ 
     ['t%s'%i for i in range(1, 6)], 
     ['h1', 'h2'] 
    ], names=['Time', 'Hospital']) 
col = pd.MultiIndex.from_product([ 
     ['heart_rate', 'blood_pressure'], 
     ['Type1', 'Type2'] 
    ], names=['metric', 'bodytype']) 
df = pd.DataFrame(
    np.random.randint(10, size=(10, 4)), 
    idx, col 
) 

df 

metric  heart_rate  blood_pressure  
bodytype   Type1 Type2   Type1 Type2 
Time Hospital          
t1 h1    6  3    8  3 
    h2    3  4    2  9 
t2 h1    5  7    7  0 
    h2    9  4    9  4 
t3 h1    8  8    7  9 
    h2    5  5    3  5 
t4 h1    0  1    5  1 
    h2    4  9    5  9 
t5 h1    0  0    1  5 
    h2    2  0    5  0 

hr = df.heart_rate 
bp = df.blood_pressure 

keys = ['heart_rate', 'blood_pressure', 'my_metric'] 
pd.concat([hr, bp, hr/bp], axis=1, keys=keys) 

       heart_rate  blood_pressure  my_metric   
bodytype   Type1 Type2   Type1 Type2  Type1  Type2 
Time Hospital               
t1 h1    6  3    8  3 0.750000 1.000000 
    h2    3  4    2  9 1.500000 0.444444 
t2 h1    5  7    7  0 0.714286  inf 
    h2    9  4    9  4 1.000000 1.000000 
t3 h1    8  8    7  9 1.142857 0.888889 
    h2    5  5    3  5 1.666667 1.000000 
t4 h1    0  1    5  1 0.000000 1.000000 
    h2    4  9    5  9 0.800000 1.000000 
t5 h1    0  0    1  5 0.000000 0.000000 
    h2    2  0    5  0 0.400000  NaN 
Verwandte Themen