【问题标题】:Pandas sample with weights带有权重的熊猫样本
【发布时间】:2019-07-29 06:05:11
【问题描述】:

我有df,我想从中抽取一些关于某些变量分布的样本。假设df['type'].value_counts(normalize=True) 返回:

0.3 A
0.5 B
0.2 C

我想做类似sampledf = df.sample(weights=df['type'].value_counts()) 这样sampledf ['type'].value_counts(normalize=True) 将返回几乎相同的分布。如何在这里通过频率传递字典?

【问题讨论】:

    标签: pandas sample


    【解决方案1】:

    Weights 必须将series of the same length 作为原始df,因此最好将其添加为列:

    df['freq'] = df.groupby('type')['type'].transform('count')
    sampledf = df.sample(weights = df.freq)
    

    或者不加列:

    sampledf = df.sample(weights = df.groupby('type')['type'].transform('count'))
    

    【讨论】:

      【解决方案2】:

      除了上面的答案,需要注意的是,如果你想对每种类型进行平均采样,你应该将你的代码调整为:

      df['freq'] = 1./df.groupby('type')['type'].transform('count')
      sampledf = df.sample(weights = df.freq)
      

      在两个类的情况下。如果你有两个以上的类,你可以使用下面的代码来概括权重计算:

      w_j=n_samples / (n_classes * n_samples_j)
      

      【讨论】:

        猜你喜欢
        • 2013-05-10
        • 1970-01-01
        • 2018-10-20
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        • 2020-11-17
        • 2014-11-24
        • 2017-06-10
        相关资源
        最近更新 更多