Home »
Python »
Python Programs
How to fix array with rows of different lengths by filling the empty elements with zeros?
Learn, how can we fix array with rows of different lengths by filling the empty elements with zeros?
Submitted by Pranit Sharma, on March 07, 2023
Initializing empty array of given length
Suppose that we are given an array where each row has a different length and we need to fill the empty elements with zero to make the length of all rows equal.
To fix array with rows of different lengths by filling the empty elements with zeros, we can define a function where we will first extract the length of all the rows and then we will create a mask of length wherever the filling of zeroes is necessary.
We will then set up an output array and put elements from data into masked positions and call this function to fill the rows with zeros.
Let us understand with the help of an example,
Python code to fix array with rows of different lengths by filling the empty elements with zeros
# Import numpy
import numpy as np
# Defining a function
def fun(a):
leng = np.array([len(i) for i in a])
mask = np.arange(leng.max()) < leng[:,None]
res = np.zeros(mask.shape)
res[mask] = np.concatenate(a)
return res
# Filling required rows with 0's
res = fun([[1, 2, 3, 4],[2, 3, 1],[5, 5, 5, 5, 8 ,9 ,5],[1, 1]])
# Display result
print("Result:\n",res,"\n")
Output:
Python NumPy Programs »