我想“仅”从“标签”列中的 class=1 中采样 2 行。
在我的代码中你会看到:
1)我对 class=1 中的所有行进行采样(4 行)
2)然后我从前一个数据帧中采样 2 行
但我确信一定有更好的方法来做到这一点。
# Creation of the dataframe
df = pd.DataFrame(np.random.rand(12, 5))
label=np.array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
df['label'] = label
# Sampling
df1=df.loc[df['label'] == 1] #Extract ALL samples with class=1
df2 = pd.concat(g.sample(2) for idx, g in df1.groupby('label')) #Extract 2 samples from df1
df2
TL;博士
df = df[df.label == '1'].sample(2)
步骤
df.label == '1'
将返回与标签列等于“1”的所有行相对应的布尔值列表。在您的示例中,您只有前 4 行标记为“1”,因此返回的列表应该是:
Index Bool
0 True
1 True
2 True
3 True
4 False
5 False
6 False
...
当您将其传递到数据帧时,它只会获取上面索引为
True
的样本:
df = df[df.label == '1'].sample(2)