Skip to content
Advertisement

Is there a way to write a python function that will create ‘N’ arrays? (see body)

I have an numpy array that is shape 20, 3. (So 20 3 by 1 arrays. Correct me if I’m wrong, I am still pretty new to python)

I need to separate it into 3 arrays of shape 20,1 where the first array is 20 elements that are the 0th element of each 3 by 1 array. Second array is also 20 elements that are the 1st element of each 3 by 1 array, etc.

I am not sure if I need to write a function for this. Here is what I have tried: Essentially I’m trying to create an array of 3 20 by 1 arrays that I can later index to get the separate 20 by 1 arrays.

a = np.load() #loads file
num=20 #the num is if I need to change array size
num_2=3
for j in range(0,num):
    for l in range(0,num_2):
        array_elements = np.zeros(3)
        array_elements[l] = a[j:][l]
        

This gives the following error: ”’ ValueError: setting an array element with a sequence ”’ I have also tried making it a dictionary and making the dictionary values lists that are appended, but it only gives the first or last value of the 20 that I need.

Advertisement

Answer

Essentially you want to group your arrays by their index. There are plenty of ways of doing this. Since numpy does not have a group by method, you have to horizontally split the arrays into a new array and reshape it.

old_length = 3
new_length = 20
a = np.array(np.hsplit(a, old_length)).reshape(old_length, new_length)

Edit: It appears you can achieve the same effect by rotating the array -90 degrees. You can do this by using rot90 and setting k=-1 or k=3 telling numpy to rotate by 90 k times.

a = np.rot90(a, k=-1)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement