有点坑的 np.array_split
2020-03-12 18:39
260 查看
假如我们想要把一个 array-like 的东西拆分成多个小组(或者叫 bucket),给定组的数目或者组的大小,最后一组不足则保持原样。
那么我们想到的可能是
np.array_split()函数。我们使用其官方例子来说明一下。
例子 1:
把一个含有 8 个元素的列表拆分成 3 组,那么
np.array_split()的结果是:
>>> x = np.arange(8.0) >>> np.array_split(x, 3) [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
例子 2:
上面的结果好像看起来没啥问题,那么如果列表中含有 7 个元素呢?
>>> x = np.arange(7.0) >>> np.array_split(x, 3) [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5., 6.])]
结果每组的大小是 322,很明显不是我们想要的结果,我们想要的结果是 331。
再次查看官方文档,可以看到如下关于该函数如何拆分的解释:
For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.
也就是说,对于一个长度为
l的数组,该函数是这么拆的:前
l % n个组的大小是
l // n + 1,剩下组的大小是
l // n。 其中
//表示下取整,即
np.floor()。
对于例子 1,
l为 8,
n为 3,前
8 % 3 = 2个组的大小为
8 // 3 + 1 = 3,剩下组的大小为
8 // 3 = 2。
对于例子 2,
l为 7,
n为 3,前
7 % 3 = 1个组的大小为
7 // 3 + 1 = 3,剩下组的大小为
7 // 3 = 2。
所以,从直观上来讲,该函数倾向于使得拆分后的组大小分布更为「均衡」,有时候可能不是我们想要的结果,值得注意。
另外,还有一个和
np.array_split比较相似的函数:
np.split(),这两个函数的唯一区别是
split()必须是等分,否则会抛出异常:
ValueError: array split does not result in an equal division。
Reference
END
- 点赞 2
- 收藏
- 分享
- 文章举报
相关文章推荐
- np.array_split()与np.split()
- np.array_split()&np.split()
- Leetcode 649, Split Array to Consecutive Subsequences
- leetcode(410):Split Array Largest Sum
- Split Ruby array into sub array with slash
- Split Array Largest Sum 二分查找应用 C实现
- 659. Split Array into Consecutive Subsequences
- python 里 np.array 的shape (2,)与(2,1)的分别是什么意思,区别是什么?
- numpy给array增加维度np.newaxis的实例
- LeetCode No.410 Split Array Largest Sum
- np.array和np.asarray区别
- leetcode题解-410. Split Array Largest Sum
- How to sensibly split an array around an object
- 659. Split Array into Consecutive Subsequences
- JS Array创建及concat()split()slice()的使用方法
- 410. Split Array Largest Sum
- How to split a string to array in objective-c?
- 使用Split分割字符串出现数组越界异常java.lang.ArrayIndexOutOfBoundsException
- numpy: np.asarray 函数
- Split Array into Consecutive Subsequences