Eka
Eka

Reputation: 15002

How to dynamically create 3d numpy arrays from 2d numpy arrays using for loop

I want to create a 3d numpy array form 2d numpy array using for loop.I tried in many different methods to create 3d arrays from 2d but each time its giving me errors. This is what I have done, the end array should have a dimension of (10,3,3).

#this is a sample code
arr=[]
for i in range(10):
    a=np.random.rand(3,3)
    arr=np.stack(a,arr)
    #arr=np.append(arr,a)
    #arr=np.array([arr,a])
    #arr[i]=a

Upvotes: 2

Views: 2993

Answers (1)

akuiper
akuiper

Reputation: 215117

You can append the 2d arrays to the arr list using list.append method, and after you are done with the for loop, convert arr to 3d array by wrapping it with np.array:

arr = []
for i in range(10):
    a = np.random.rand(3,3)
    arr.append(a)

np.array(arr).shape
# (10, 3, 3)

Or numpy.stack:

np.stack(arr).shape
# (10, 3, 3)

Upvotes: 3

Related Questions