我有一个数组,它给出了一些其他数字的累积百分比:
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]]
似乎应该有一个聪明的方法来有效地做到这一点。
请您参考如下方法:
问题没有明确定义,但看起来很有趣。下面将一个数组 (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]
而 block 的总和是:
print [np.sum(x) for x in chunks]
[27.93830, 29.51562, 28.30718, 29.23604, 28.7935]
