根据列的分布随机采样熊猫数据帧
问题内容:
假设我有一个非常大的数据框,我想对其进行采样以尽可能接近该数据框的列的分布(在本例中为“ bias”列)。
我跑:
train['bias'].value_counts(normalize=True)
并看到:
least 0.277220
left 0.250000
right 0.250000
left-center 0.141244
right-center 0.081536
如果我想从样本的“ bias”列的分布与该分布匹配的火车数据帧中抽取一个样本,那么最好的方法是什么?
问题答案:
您可以从文档中使用sample:
从对象轴返回随机的项目样本。
诀窍是在每个组中使用样本,一个代码示例:
import pandas as pd
positions = {"least": 0.277220, "left": 0.250000, "right": 0.250000, "left-center": 0.141244, "right-center": 0.081536}
data = [['title-{}-{}'.format(i, position), position] for i in range(1000) for position in positions.keys()]
frame = pd.DataFrame(data=data, columns=['title', 'position'])
print(frame.shape)
def sample(obj, replace=False, total=1000):
return obj.sample(n=int(positions[obj.name] * total), replace=replace)
result = frame.groupby('position', as_index=False).apply(sample).reset_index(drop=True)
print(result.groupby('position').agg('count'))
输出量
(5000, 2)
title
position
least 277
left 250
left-center 141
right 250
right-center 81
在上面的示例中,我创建了一个具有5000行2列的数据框,这是输出的第一部分。
我假设您有一个位置字典(要将DataFrame转换为字典,请参见this),其中包含要从每个组中采样的百分比和一个总参数(即要采样的总数)。
在输出的第二部分中,您可以看到100个最小的277行277 / 1000 = 0.277
。这是所需数量的近似值,其余组也是如此。需要注意的是,样本数为999,而不是预期的1000。