![](/img/trans.png)
[英]Remove random N number of rows based on conditions on multiple columns in pandas
[英]Pandas dataframe, select n random rows based on number of unique values
我正在研究一個訓練良好的文本分類問題,但我的類別非常不平衡,阻礙了結果。 最大的 2 個類別比最小的類別大 80 倍以上,因此 go 對這 2 個類別的分類數量不公平。 我需要每個類別的 select n
行(任意大)。 我的數據集非常大(10m 行,1k 個唯一類別)。
假設 dataframe 是:
data = {
'category':['2','2','2','2','4','4','4','4','4','4','6','6','6'],
'text':['t1','t2','t3','t4','t5','t6','t7','t8','t9','t10','t11','t12','t13']
}
df = pd.DataFrame(data)
我怎么能 select 每個類別有n
隨機行?
我試圖找到某種方法來使用np.random.choice
到 select n
隨機行,但我找不到一種方法來獲取該索引以逐個索引。
n = 3
的理想 output 將類似於:
>>> df.head(9)
category text
0 2 t3
1 6 t11
2 6 t13
3 4 t6
4 2 t1
5 4 t9
6 4 t8
7 2 t4
8 6 t12
您可以使用sample
和groupby().head()
:
df.sample(frac=1).groupby('category').head(3)
Output:
category text
4 4 t5
12 6 t13
1 2 t2
8 4 t9
9 4 t10
3 2 t4
10 6 t11
0 2 t1
11 6 t12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.