简体   繁体   English

如何将numpy数组拆分为python中单独的arrays。拆分数量由用户给出,拆分基于索引

[英]How to split the numpy array into separate arrays in python. The number is splits is given by the user and the splitting is based on index

I want to split my numpy array into separate arrays. The separation must be based on the index.我想将我的 numpy 数组拆分成单独的 arrays。分隔必须基于索引。 The split count is given by the user.拆分计数由用户给出。

For example, The input array: my_array=[1,2,3,4,5,6,7,8,9,10]例如,输入数组: my_array=[1,2,3,4,5,6,7,8,9,10]

If user gives split count =2, then, the split must be like如果用户给出拆分计数 =2,则拆分必须像

my_array1=[1,3,5,7,9]
my_array2=[2,4,6,8,10]

if user gives split count=3, then the output array must be如果用户给出 split count=3,则 output 数组必须是

my_array1=[1,4,7,10]
my_array2=[2,5,8]
my_array3=[3,6,9]

could anyone please explain, I did for split count 2 using even odd concept任何人都可以解释一下,我使用偶数概念为拆分计数 2 做了

for i in range(len(outputarray)):
    if i%2==0:
        even_array.append(outputarray[i])  
    else:
        odd_array.append(outputarray[i])

I don't know how to do the split for variable counts like 3,4,5 based on the index.我不知道如何根据索引对 3、4、5 等变量计数进行拆分。

Here is a python-only way of doing your task这是完成任务的仅限 python 的方法

def split_array(array, n=3):
    arrays = [[] for _ in range(n)]
    for x in range(n):
        for i in range(n):
            arrays[i] = [array[x] for x in range(len(array)) if x%n==i]
    return arrays

Input:输入:

my_array=[1,2,3,4,5,6,7,8,9,10]
print(split_array(my_array, n=3))

Output: Output:

[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

You can use indexing by vector (aka fancy indexing ) for it:您可以为其使用按向量索引(又名花式索引):

>>> a=np.array([1,2,3,4,5,6,7,8,9,10])
>>> n = 3
>>> [a[np.arange(i, len(a), n)] for i in range(n)]

[array([ 1,  4,  7, 10]), array([2, 5, 8]), array([3, 6, 9])]

Explanation解释

arange(i, len(a), n) generates an array of integers starting with i , spanning no longer than len(a) with step n . arange(i, len(a), n)生成一个以i开头的整数数组,跨度不超过len(a) ,步长n For example, for i = 0 it generates an array例如,对于i = 0 ,它生成一个数组

 >>> np.arange(0, 10, 3)
 array([0, 3, 6, 9])

Now when you index an array with another array, you get the elements at the requested indices:现在,当您使用另一个数组索引一个数组时,您会在请求的索引处获得元素:

 >>> a[[0, 3, 6, 9]]
 array([ 1,  4,  7, 10])

These steps are repeated for i=1..2 resulting in the desired list of arrays.对 i=1..2 重复这些步骤,得到所需的列表 arrays。

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

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