Reshape 3-D numpy array to 1-D array:
I would like to reshape a 3-D array that looks like this:
test_3d = np.array([[[0., 0.],
[1., 1.]],
[[2., 2.],
[3., 3.]]])
To a 1-D array that looks like this:
array([0., 1., 2., 3., 0., 1., 2., 3.])
Flattening the array using test_3d.flatten()
outputs:
array([0., 0., 1., 1., 2., 2., 3., 3.])
A combination of np.flatten/ravel and transpose functionalities work well for 2-D arrays, but for a 3-D array I get the following:
Input:
test_3d.T.flatten()
Output:
array([0., 2., 1., 3., 0., 2., 1., 3.])
Does anybody have any ideas?
To present a more instructive example, I defined test_3d as:
test_3d = np.array(
[[[0., 10.],
[1., 11.]],
[[2., 12.],
[3., 13.]]])
(now you can tell apart both "initial" zeroes).
To get your expected result, run:
result = np.transpose(test_3d, (2, 0, 1)).flatten()
The result is:
array([ 0., 1., 2., 3., 10., 11., 12., 13.])
An alternative solution is:
result = np.rollaxis(test_3d, 2).flatten()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.