[英]add column from another data frame if the value falls under the range from the other data frame using pandas
[英]determine the quantile a value falls in, in a Pandas data frame
我有一個包含幾列的pandas數據框。 對於每列,我想計算某些百分位數。 然后我想用每個觀察值所在的百分位替換我的數據框。
import pandas as pd
M = np.random.uniform(0, 100, (10, 6))
df = pd.DataFrame(M, columns=['c%i'%i for i in range(6)])
>>> df[:2]
c0 c1 c2 c3 c4 c5
0 24.883165 2.299054 11.002427 98.711018 39.042343 50.408190
1 42.099085 78.028507 25.099002 39.099628 38.687483 15.794404
df.quantile([.1, .5, .9])
c0 c1 c2 c3 c4 c5
0.1 21.418274 7.094343 10.904711 25.014356 15.958873 21.984237
0.5 41.793102 36.973471 29.031637 64.246471 41.136274 42.408574
0.9 75.724554 62.274133 86.604768 93.690257 73.757992 89.365606
例如,在第0行中,c0 = 24.883。 最大的c0分位數q_c0,其中24.883 <= q_c0將是0.5。 在我的新數據框架中,我想要用0.5替換24.883。
如何使用qcut()
:
import pandas as pd
import numpy as np
M = np.random.uniform(0, 100, (10, 6))
df = pd.DataFrame(M, columns=['c%i'%i for i in range(6)])
bins = [0.0, 0.1, 0.5, 0.9, 1.0]
df.apply(lambda s:pd.qcut(s, bins, bins[1:]).astype(float))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.