Python 根据顺序将数组拆分为等重块

Python 根据顺序将数组拆分为等重块,python,arrays,numpy,Python,Arrays,Numpy,我有一个数组,它给出了一些其他数字的累积百分比: my_cumulative_array = np.asarray(range(0,50))/float(50) 我想将此数组拆分为n组,每组的权重相等: chunks = [[row indexes 01-10], #First 20% based on order [row indexes 11-20], #Second 20% based on order [row indexes

我有一个数组,它给出了一些其他数字的累积百分比:

my_cumulative_array = np.asarray(range(0,50))/float(50) 
我想将此数组拆分为n组,每组的权重相等:

chunks    = [[row indexes 01-10], #First 20% based on order
            [row indexes 11-20],  #Second 20% based on order
            [row indexes 21-30],
            [row indexes 31-40],
            [row indexes 41-50]]

似乎应该有一个聪明的方法来有效地做到这一点

从您的示例输出来看,它似乎是您要查找的

chunks = [my_cumulative_array[i*(50/n):(i+1)*(50/n)] for i in range(n)]

这个问题没有很好的定义,但看起来很有趣。下面将数组(
arr
)拆分为数组列表(
chunks
),其中
chunks
中的每个数组的总和大致相等

splits = 5
arr = np.sin(np.random.rand(100)) + np.arange(100)/50.0
cum_arr = arr.cumsum() / arr.sum()
idx = np.searchsorted(cum_arr, np.linspace(0, 1, splits, endpoint=False)[1:])
chunks = np.split(arr, idx)
我们可以观察到,分割指数的间距不是相等的:

print idx
[37 59 74 88]
而区块的总和为:

print [np.sum(x) for x in chunks]
[27.93830, 29.51562, 28.30718, 29.23604, 28.7935]

所以,不同的块会有不同数量的元素,对吗?因为你的累积百分位值是线性增加的,而且数组的大小可以被5整除,所以你给出的例子中一个简单的解决方案就是将
my_cumulative_percentile
分成5个相等的块,例如
np.split(my_cumulative_percentile,5)
,或者要获得相应的索引,
np.split(np.arange(my_cumulative_percentile.shape[0]),5)
。这就是您想要的,还是您的实际问题更复杂?块可以是不同的大小。很抱歉,我的示例线性增加了,但第一组可能最终包含20%的元素(代表基础可变权重的10%)或1个元素(也代表基础可变权重的10%。您好,欢迎来到StackOverflow上的
numpy
板。一般来说,由于性能问题,不鼓励python回答numpy问题。尤其是当用户正在寻找有效的解决方案时。啊,感谢您提供的信息!我会记住这一点。这非常完美!非常感谢