gpt4 book ai didi

python - 根据顺序将数组拆分为同等权重的 block

转载 作者:太空宇宙 更新时间:2023-11-04 08:52:44 24 4
gpt4 key购买 nike

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

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]

关于python - 根据顺序将数组拆分为同等权重的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555496/

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