I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.
data = [0,4,1,3,2,5,9,6,7,8]
array([[ 0, 4, 1, 3],
[ 2, 5, 9, 6],
[ 7, 8, -1, -1]])
data += [-1]*(row*col - len(data))
output = np.array(data).reshape((row, col))
data + [-1]*remaining
I'm sure there are various ways of doing this. My first inclination is to make a
output array filled with the 'fill', and copy the
data to it. Since the fill is 'ragged', not a full column or row, I'd start out 1d and reshape to the final shape.
In : row,col = 3,4 In : data = [0,4,1,3,2,5,9,6,7,8] In : output=np.zeros(row*col,dtype=int)-1 In : output[:len(data)]=data In : output = output.reshape(3,4) In : output Out: array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]])
Regardless of whether
data starts as a list or a 1d array, it will have to be copied to
output. With a change in the total number of characters we can't just reshape it.
This isn't that different from your approach of adding the extra values via
There is a
pad function, but it works on whole columns or rows, and internally is quite complex because it's written for general cases.