Cam K
Cam K

Reputation: 127

Fit one array into another regardless of sizes - Python

Consider numpy arrays arr1 and arr2. They can be any number of dimensions. For example

arr1=np.zeros([5,8])
arr2=np.ones([4,10])

I would like to put arr2 into arr1 either by cutting off excess lengths in some dimensions, or filling missing length with zeros.

I have tried:

arr1[exec(str(",:"*len([arr1.shape]))[1:])]=arr2[exec(str(",:"*len([arr2.shape]))[1:])]

which is basically the same as

arr1[:,:]=arr2[:,:]

I would like to do this preferably in one line and without "for" loops.

Upvotes: 0

Views: 517

Answers (2)

Cam K
Cam K

Reputation: 127

I solved this by coming up with the following. I used slice() as @hpaulj suggested. Considering I want to assign ph10 (an array) to ph14 (an array of zeros of size bound1):

ph14=np.zeros(bound1)
ph10=np.array(list1)
        
ind_min=np.min([ph14.shape,ph10.shape],0)
                           
ph24=[]
for n2 in range(0,len(ind_min.shape)):
    ph24=ph24+[slice(0,ind_min[n2])]
        
ph14[ph24]=ph10[ph24]

Upvotes: 0

Rahul Vishwakarma
Rahul Vishwakarma

Reputation: 1456

You could use this :

arr1[:min(arr1.shape[0], arr2.shape[0]), :min(arr1.shape[1], arr2.shape[1])]=arr2[:min(arr1.shape[0], arr2.shape[0]), :min(arr1.shape[1], arr2.shape[1])]

without any for loop.

It's the same concept you applied in second try, but with a condition to choose minimum length.

Upvotes: 1

Related Questions