【问题标题】:How can I sample from a dataframe weighted by groupby column如何从按 groupby 列加权的数据框中进行采样
【发布时间】:2021-06-16 10:43:33
【问题描述】:

Here 是一种抽样方法。 我试过了:

sample=2000 
sample_df = df.groupby('prefix').sample(n=sample, random_state=1)

它将df 与prefix 分组,并为每个组采样2k 个项目。我有9组。我想采样 18k,但按每组中的数字加权。

【问题讨论】:

    标签: python pandas group-by sampling


    【解决方案1】:

    IIUC,这是一种方法:

    sample = 2000
    col_name = "prefix"
    
    probs = df[col_name].map(df[col_name].value_counts())
    sample_df = df.sample(n=sample, weights=probs)
    

    probs 是prefix 列中每个值对应的(未归一化的)权重,我们据此进行采样。


    一些样本数据的步骤:

    >>> df
    
           B         C         D
    0   this  0.469112 -0.861849
    1   this -0.282863 -2.104569
    2  other -1.509059 -0.494929
    3   view -1.135632  1.071804
    4  other  1.212112  0.721555
    5  other -0.173215 -0.706771
    6   this  0.119209 -1.039575
    7   view -1.044236  0.271860
    8  other  0.322124  2.010234
    
    >>> col_name = "B"
    >>> sample = 4
    
    >>> counts = df[col_name].value_counts()
    >>> counts
    
    other    4
    this     3
    view     2
    Name: B, dtype: int64
    
    >>> probs = df[col_name].map(counts)
    >>> probs
    
    0    3
    1    3
    2    4
    3    2
    4    4
    5    4
    6    3
    7    2
    8    4
    Name: B, dtype: int64
    
    # seeing side-by-side with df.B
    >>> pd.concat([df.B, probs], axis=1)
    
    0   this  3
    1   this  3
    2  other  4
    3   view  2
    4  other  4
    5  other  4
    6   this  3
    7   view  2
    8  other  4
    

    即,col_name 中的每个值都附加了一个数字,该数字相对地衡量其权重,从其在列中的计数推断出来。

    # sampling:
    >>> sample_df = df.sample(n=sample, weights=probs, random_state=1284)
    >>> sample_df
    
           B         C         D
    6   this  0.119209 -1.039575
    3   view -1.135632  1.071804
    2  other -1.509059 -0.494929
    5  other -0.173215 -0.706771
    

    【讨论】:

    • 谢谢!你能写出来让我可以通过prefix以外的任何其他字段吗?此外,您将它们分组到哪里?
    • @Ahmad 我重新安排了用任何名称代替prefix 作为分组变量,并试图解释形成计数和非标准化权重的过程;希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2021-09-07
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多