gpt4 book ai didi

带权重的 Pandas 样本

转载 作者:行者123 更新时间:2023-12-04 11:22:36 29 4
gpt4 key购买 nike

我有 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)将返回几乎相同的分布。如何在这里通过频率传递 dict?

最佳答案

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'))

关于带权重的 Pandas 样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55042334/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com