我试图随机抽样一个 * 相对 * 大的数据集(由90 [mn]左右的数据点组成)
我想根据列“a”(大约有100 k个唯一值)对数据集进行采样,每个a都有不同的n值。
我知道有这样的东西存在:
df.groupby("a").sample(n=1, random_state=1)
字符串
但这并没有考虑到不同的n值。
接下来的想法是在循环过滤后通过a然后采样来过滤df('m '是'a'的唯一值,我正在采样):
filter_df = df.loc[(df['a'] == f)]
filter_df = filter_df.sample(n=m, random_state=6)
型
为了增加另一层潜在的复杂性,如果数据超过每组“a”的样本总数,我想对数据进行采样,否则如果样本大于replace = False
,则使用replace = True
,以便我尽可能多地选择唯一的行。
因此,在枚举的for循环中(例如,4个100 k长的单独列表,包括列“a”的唯一值,让我们称之为变量“kk”,它是一个整数:
if kk >= m:
filter_df = filter_df.sample(n=m, random_state=6)
print("sampling okay")
test["flag"] = "ok"
else:
filter_df = filter_df.sample(n=m, random_state=6,replace=True)
型
最后用concat来合并。
这是基本的想法,代码工作正常,但是,性能是次优的。想知道是否有一个矢量化的潜在解决方案,我可以使用。
为了简洁起见,样本的数量“m”是第一个df的计数:
| a
个|count
个|
| --|--|
| 1
个|1
个|
| 2
个|3
个|
| 3
个|2
|
我正在尝试从原始DF采样:
| 一|X|
| --|--|
| 1 |一|
| 1 |B|
| 1 |C|
| 2 |D|
| 2 |e|
| 3 |F|
| 3 |G|
期望的采样输出(当然采样x将是“随机”的):
| a
个|x
个|
| --|--|
| 1 |一|
| 2 |D|
| 2 |e|
| 2 |e|
| 3 |F|
| 3 |G|
2条答案
按热度按时间nkhmeac61#
从第一个数组中创建一个字典,并创建自定义分组函数:
字符串
印刷品:
型
输入框:
型
aij0ehis2#
字符串
数据
型