2

Assuming I have 3 numpy square matrices of various shapes:

AxA
BxB
CxC

Is there a numpy function which would expand the matrices to the maximum size and put some default values in new cells? Example:

3x3
5x5
10x10

should result in 3 10x10 arrays.

2
  • Does this answer your question? Good ways to "expand" a numpy ndarray? Commented Jan 18, 2020 at 1:53
  • @AMC, thanks for sharing the link. It's not exactly fitting my demands, but has useful information! Commented Jan 19, 2020 at 23:49

1 Answer 1

3

As long as you want the original values of a and b to be stored in the "upper left", you could go with initializing a new array with your wanted fill_value (say, 99) and place your smaller arrays in it like this:

import numpy as np

a = np.ones(shape=(3,3))
b = np.ones(shape=(5,5))
c = np.ones(shape=(10,10))

a2 = np.full(shape=(10,10), fill_value=99)
a2[:a.shape[0], :a.shape[1]] = a

b2 = np.full(shape=(10,10), fill_value=99)
b2[:b.shape[0], :b.shape[1]] = b

##

>> a2:
[[ 1  1  1 99 99 99 99 99 99 99]
 [ 1  1  1 99 99 99 99 99 99 99]
 [ 1  1  1 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]]

Edit:

If you want to do this automatically, without having to know the dimension of the largest square array:

a = np.ones(shape=(3,3))
b = np.ones(shape=(5,5))
c = np.ones(shape=(10,10))

list_of_arrays = [a, b, c]
shapes = [arr.shape for arr in list_of_arrays]
max_shape = max(shapes)

for iarr, arr in enumerate(list_of_arrays):
    arr_new = np.full(shape=max_shape, fill_value=99)
    arr_new[:arr.shape[0], :arr.shape[1]] = arr
    list_of_arrays[iarr] = arr_new


>> print(list_of_arrays[1])
[[ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.