【问题标题】:random sample per group, with min_rows每组随机样本,min_rows
【发布时间】:2020-12-27 20:53:45
【问题描述】:

我有一个数据框,我想对其进行采样。但是,在随机抽样时,我希望从列中的每个元素中至少有 1 个样本。我也希望分布也有效果。(例如:原始样本更多的值对采样的df有更多)

类似于thisthis 问题,但每组的样本量最少。

假设这是我的 df:

df = pd.DataFrame(columns=['class'])
df['class'] = [0,0,0,0,0,0,0,0,0,0,0,0,0,1,2]
df_sample = df.sample(n=4)

当我对此进行采样时,我希望 df_sample 看起来像:

     Class
      0
      0
      1
      2

谢谢。

【问题讨论】:

  • 如何使用 set 获取所有唯一项目,然后使用 sample(n=len(set) -prev_n) 从数据中采样。

标签: python pandas sample


【解决方案1】:

按照@YukiShioriii 的建议,您可以:

1 - 对每组值的一行进行采样

2 - 对剩余的行进行随机抽样,而不考虑值

【讨论】:

    【解决方案2】:

    听从 YukiShioriii 和 mprouveur 的建议

    # random_state for reproducibility, remove in production code
    sample = df.groupby('class').sample(1, random_state=1)
    
    sample = sample.append(
        df[~df.index.isin(sample.index)] # only rows that have not been selected
        .sample(n=sample_size-sample.shape[0]) # sample more rows as needed
    ).sort_index()
    

    输出

        class
    2       0
    4       0
    13      1
    14      2
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 2022-12-09
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2018-11-02
      • 2016-09-06
      • 1970-01-01
      相关资源
      最近更新 更多