Mam dataframe, który wygląda tak:Python: ważona mediana algorytm z pand
Out[14]:
impwealth indweight
16 180000 34.200
21 384000 37.800
26 342000 39.715
30 1154000 44.375
31 421300 44.375
32 1210000 45.295
33 1062500 45.295
34 1878000 46.653
35 876000 46.653
36 925000 53.476
Chcę obliczyć ważoną medianę kolumnie impwealth
wykorzystaniem wagi częstotliwości w indweight
. Mój pseudo kod wygląda następująco:
# Sort `impwealth` in ascending order
df.sort('impwealth', 'inplace'=True)
# Find the 50th percentile weight, P
P = df['indweight'].sum() * (.5)
# Search for the first occurrence of `impweight` that is greater than P
i = df.loc[df['indweight'] > P, 'indweight'].last_valid_index()
# The value of `impwealth` associated with this index will be the weighted median
w_median = df.ix[i, 'impwealth']
Ta metoda wydaje się niezgrabne, i nie jestem pewien, że to poprawne. Nie znalazłem wbudowanego w to sposobu w odniesieniu do pand. Jaki jest najlepszy sposób na znalezienie ważonej mediany?
Czy jesteś pewien kod pseudo jest poprawna? 'df ['indweight']. sum() * (.5)' da wartość ~ 219', której nie przekroczy żadna z wartości 'indweight'. Wywołanie 'df ['indweight']. Median()' daje 44.835 i 'mean()' daje 43.783 – EdChum
Myślę, że tak .. 'df ['indweight']. Sum() * (.5)' należy obliczyć liczba obserwacji, które mieszczą się w 50. percentylu danych, ponieważ "indweight" jest masą częstotliwości. Więc ma sens, że średnia i mediana "indats" przewyższają jej sumę. – svenkatesh
@svenkatesh, musisz użyć '' .cumsum() '' z '' indweight'', a nie '' indweight''. Zobacz moją odpowiedź poniżej, być może. – prooffreader