首页 > 解决方案 > pandas:从给定的 bin 中生成数字

问题描述

情况:

scope = np.arange(0,1000)  

我想要一个带有分布的熊猫系列:

10% 随机数从 0 到 200
10% 随机数从 201 到 500
80% 随机数从 501 到 999

熊猫系列中的数字未排序

标签: pythonpandasnumpy

解决方案


假设您想要一个长度为 100 的系列,您可以这样做:

import numpy as np
import pandas as pd

np.random.seed(42)

length = 100
low = np.random.randint(0, 201, length // 10)  # 10%
mid = np.random.randint(201, 501, length // 10) # 10%
high = np.random.randint(501, 1000, 8 * (length // 10)) # 80%

# shuffle the data to make un-ordered across bins
data = np.concatenate([low,  mid, high])
np.random.shuffle(data)

res = pd.Series(data=data)

# just to verify
print("0 - 200", (res < 201).sum())
print("201 - 500", ((res > 200) & (res < 501)).sum())
print("501 - 1000", ((res > 501) & (res < 1000)).sum())

输出

0 - 200 10
201 - 500 10
501 - 1000 80

推荐阅读