![](/img/trans.png)
[英]Filter pandas dataframe based on a column: keep all rows if a value is that column
[英]Sample dataframe by value in column and keep all rows
我想使用某個列中的值對 Pandas dataframe 進行采樣,但我想保留樣本中的值的所有行。
例如,在下面的 dataframe 中,我想隨機抽取b
中值的一部分,但保留a
和c
中的所有相應行。
d = pd.DataFrame({'a': range(1, 101, 1),'b': list(range(0, 100, 4))*4, 'c' :list(range(0, 100, 2))*2} )
來自 16% 樣本的所需示例 output:
Out[66]:
a b c
0 1 0 0
1 26 0 50
2 51 0 0
3 76 0 50
4 4 12 6
5 29 12 56
6 54 12 6
7 79 12 56
8 18 68 34
9 43 68 84
10 68 68 34
11 93 68 84
12 19 72 36
13 44 72 86
14 69 72 36
15 94 72 86
我已經嘗試對系列進行采樣並合並回主要數據,如下所示:
In [66]: pd.merge(d, d.b.sample(int(.16 * d.b.nunique())))
這將創建所需的 output,但似乎效率低下。 我的真實數據集在b
中有數百萬個值和數億行。 我知道我也可以使用一些版本的“isin”,但這也很慢。
有沒有更有效的方法來做到這一點?
我真的懷疑isin
很慢:
uniques = df.b.unique()
# this maybe the bottle neck
samples = np.random.choice(uniques, replace=False, size=int(0.16*len(uniques)) )
# sampling here
df[df.b.isin(samples)]
您可以分析上述步驟。 如果samples=...
很慢,您可以嘗試:
idx = np.random.rand(len(uniques))
samples = uniques[idx<0.16]
這些在我的系統上花費了大約 100 毫秒,有 1000 萬行。
注意: dbsample(int(.16 * dbnunique()))
不會對b
中的0.16
個唯一值進行采樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.