Zero Pad Array Based On Other Array's Shape
I've got K feature vectors that all share dimension n but have a variable dimension m (n x m). They all live in a list together. to_be_padded = [] to_be_padded.append(np.reshape(
Solution 1:
You could use np.pad
for that, which can also pad 2-D
arrays using a tuple of values specifying the padding width, ((top, bottom), (left, right))
. For that you could define:
defpad_to_length(x, m):
return np.pad(x,((0, 0), (0, m - x.shape[1])), mode = 'constant')
Usage
You could start by finding the ndarray
with the highest amount of columns. Say you have two of them, a
and b
:
a = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
b = np.array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
m = max(i.shape[1] for i in [a,b])
# 5
And then use this parameter to pad the ndarrays
:
pad_to_length(a, m)
array([[0, 1, 2, 0, 0],
[3, 4, 5, 0, 0],
[6, 7, 8, 0, 0]])
Solution 2:
I believe there is no very efficient solution for this. I think you will need to loop over the list with a for loop and treat every array individually:
for i in range(len(to_be_padded)):
padded = np.zeros((n, maxM))
padded[:,:to_be_padded[i].shape[1]] = to_be_padded[i]
to_be_padded[i] = padded
where maxM
is the longest m
of the matrices in your list.
Post a Comment for "Zero Pad Array Based On Other Array's Shape"