将数据集样本转换为相等的正样本和负样本

时间:2018-01-21 01:03:55

标签: python pandas dataframe machine-learning

我正在尝试以高效的方式获取大量数据集的样本,其中+ ve样本的数量= -ve样本的数量。

数据的比例是4:2 + ve到-ve所以我试图制作一个样本,其中数据的比例为2:2

    A   B   C class   
0   0   1   2   0
1   3   4   5   0
2   6   7   8   1
3   9   10  11  1
4   12  13  14  1
5   15  16  17  1

期望的输出:

    A   B   C   class   
0   0   1   2   0
1   3   4   5   0
2   6   7   8   1
3   9   10  11  1

我尝试使用pandas value_counts func使用python代码对其进行采样,但它不具有内存效率。

1 个答案:

答案 0 :(得分:0)

positive=data[data['class']==0]
negative=data[data['class']==1].sample(n=positive.shape[0])
final=pd.concat([positive,negative])

positive_len=np.sum(data['class']==0) #gives the number of rows with class=0
final=data.sort_values('class')[:2*positive_len] #sort values. now rows with class 0 are on the top, rows with class 1 are on the bottom. pick top 2* length of positive.