简体   繁体   English

将2D numpy数组垂直拆分为不均匀的子数组

[英]Split 2D numpy array vertically into uneven subarrays

Suppose I have the following numpy array of shape (10, 5) where I want to split it into two subarrays: the first one contains the first 7 rows and the second one takes the remaining 3 rows. 假设我有以下形状(10, 5) numpy数组,我想将其拆分成两个子数组:第一个包含前7行,第二个包含其余3行。 If I do this: 如果我这样做:

x = np.arange(50).reshape(10, 5)
x1, y1 = np.vsplit(x, 2)

It will split exactly half. 它将精确地分开一半。 How can I make it two subarrays (7,5) and (3,5) ? 我如何使其成为两个子数组(7,5)(3,5)

Use np.split() : 使用np.split()

In [4]: np.split(x, [7])
Out[4]: 
[array([[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34]]), array([[35, 36, 37, 38, 39],
        [40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49]])]

i think you shhould use fancy indexing, unlike slicing, fancy indexing always copies the data into a new array 我认为您应该使用奇特索引,而不像切片,奇特索引总是将数据复制到新数组中

n = 10; m = 5; i = 7
arr = np.arange(50).reshape(n, m)
arr7 = arr[np.ix_(range(i))]
arr3 = arr[np.ix_(range(i - n, 0, 1))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM