python - 不同类别的随机抽样
问题描述
我在这个领域是全新的。我试图找到解决方案,但不能完全像这样。我正在使用 pandas库在python Jupyter中编写代码。我知道采样的代码。这是df = data.sample(frac =.1)
但无法理解如何为此编写代码。
数据集:
我有这个数据集。我想从每个类(环)中随机选择 2 行。以下是预期的输出:
解决方案
您可以执行以下操作:
设置
import numpy as np
import pandas as pd
np.random.seed(42)
df = pd.DataFrame({"Shell(g)": np.random.random(14), "Rings": [3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6]})
代码
# shuffle
result = df.sample(frac=1.0)
# get the first two by group
result = result.groupby("Rings").head(2)
# sort by Rings
result = result.sort_values("Rings")
print(result)
输出
Shell(g) Rings
1 0.950714 3
0 0.374540 3
3 0.598658 4
2 0.731994 4
7 0.866176 5
6 0.058084 5
12 0.832443 6
10 0.020584 6