How to drop columns in those 2D numpy arrays that have more than N columns?

Viewed 28

I have 3 different 2D numpy arrays, each having a different number of columns:

import numpy as np

arr1 = np.random.randn(10, 5)
arr2 = np.random.randn(10, 6)
arr3 = np.random.randn(10, 4)

Now I want to merge these 3 2D arrays into a single 3D array:

myList = []
myList.append(arr1)
myList.append(arr2)
myList.append(arr3)

3darr = np.dstack(myList)

However, since the arrays have different number of columns, I get an error:

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 6

How can I create a 3D array by taking the minimum number of columns across the 3 2D arrays? In other words, the minimum number of columns across the 3 2D arrays is equal to 4. Thus, I want to drop the columns after 4th in all 2D arrays that have more than 4 columns.

1 Answers

hope following could help.

import numpy as np
a = []
a.append(np.random.randn(10, 5))
a.append(np.random.randn(10, 6))
a.append(np.random.randn(10, 4))
k = min([i.shape[1] for i in a])
out = np.zeros((a[0].shape[0], k, len(a)))
for ind in range(len(a)):
    out[:,:,i] = a[i][:,:k]
Related