How to manipulate multidimensional numpy array in python
Solution 1:
If the array is arr
then you can use:
np.pad(arr, ((0, 1), (1, 0)))
Solution 2:
You can insert 0
at the beginning of every array and then append a list of 22 0
.
import numpy as np
data = np.array([[0., 2073., 2352., 1119., 2074., 1344., 4035., 1980., 2213.,
2363., 2655., 2322., 1148., 2046., 2234., 1076., 1647.,
2957.,
1968., 2246., 1723.],
[1517., 0., 891., 1537., 1993., 2231., 2574., 689., 1561.,
2157., 1517., 3275., 1566., 757., 774., 2190., 822., 1355.,
2152., 1575., 1064.],
[1597., 1329., 0., 1617., 1106., 1345., 1951., 1551., 1938.,
1270., 629., 2320., 1646., 1619., 862., 2267., 1357., 934.,
1264., 687., 342.]])
updated = np.insert(data, 0, 0, axis=1)
updated = np.append(updated, [[0] * 22], axis=0)
print(updated)
Output:
[[ 0. 0. 2073. 2352. 1119. 2074. 1344. 4035. 1980. 2213. 2363. 2655.
2322. 1148. 2046. 2234. 1076. 1647. 2957. 1968. 2246. 1723.]
[ 0. 1517. 0. 891. 1537. 1993. 2231. 2574. 689. 1561. 2157. 1517.
3275. 1566. 757. 774. 2190. 822. 1355. 2152. 1575. 1064.]
[ 0. 1597. 1329. 0. 1617. 1106. 1345. 1951. 1551. 1938. 1270. 629.
2320. 1646. 1619. 862. 2267. 1357. 934. 1264. 687. 342.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
Explanation:
- We have inserted in
axis
1 to add0
in the existing multidimensional array. - We have appended the list of 22 0's to
axis
0 at the end.
References:
- Numpy documentation on insert method
- Numpy documentation on append method