如何从 python 中的特定类中采样行数?

问题描述 投票:0回答:2

我想“仅”从“标签”列中的 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

python-3.x pandas numpy
2个回答
4
投票

我就这样做:

df1.query('label == 1').sample(2)


0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.