python - How to fix error when concatenating two numpy arrays? -
i trying following:
rands = np.empty((0, 10)) rand = np.random.normal(1, 0.1, 10) rands = np.concatenate((rands,rand),axis=0) which gives me following error:
valueerror: input arrays must have same number of dimensions but why error? why can't append new row rand matrix rands command?
remark:
i can 'fix' using following command:
rands = np.concatenate((rands,rand.reshape(1, 10)),axis=0) but looks not pythonic anymore, cumbersome...
maybe there better solution less brackets , reshaping...?
rands has shape (0, 10) , rand has shape (10,).
in [19]: rands.shape out[19]: (0, 10) in [20]: rand.shape out[20]: (10,) if try concatenate along 0-axis, 0-axis of rands (of length 0) concatenated 0-axis of rand (of length 10). pictorially, looks this:
rands:
| | | | | | | | | | | rand:
| | | | | | | | | | | | | | | | | | | | the 2 shapes not fit because 1-axis of rands has length 10 , rand lacks 1-axis.
to fix problem, promote rand 2d array of shape (1, 10):
in [21]: rand[none,:].shape out[21]: (1, 10) so 10 items in rand laid out along 1-axis.
rands = np.concatenate((rands,rand[none,:]), axis=0) returns array of shape (1, 10)
in [26]: np.concatenate((rands,rand[none,:]),axis=0).shape out[26]: (1, 10) alternatively, use row_stack without promoting rand 2d array:
in [28]: np.row_stack((rands,rand)).shape out[28]: (1, 10)
Comments
Post a Comment