Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding dimension to ndarray and reshaping

I have a numpy array that has shape of (16,2)

[[-109.12722222    1454.        ]
 [-109.12694444    1459.        ]
 [-109.12666667    1463.        ]
 [-109.12638889    1465.        ]
 [-109.12611111    1464.        ]
 [-109.12583333    1464.        ]
 [-109.12555556    1464.        ]
 [-109.12527778    1464.        ]
 [-109.125         1464.        ]
 [-109.12472222    1465.        ]
 [-109.12444444    1465.        ]
 [-109.12416667    1463.        ]
 [-109.12388889    1462.        ]
 [-109.12361111    1461.        ]
 [-109.12333333    1459.        ]
 [-109.12305556    1454.        ]]

and I want to know how to reshape it so it is (4,4,2).

[[-109.12722222    1454.        ] [-109.12694444    1459.        ][-109.12666667    1463.        ][-109.12638889    1465.        ]
 [-109.12611111    1464.        ] [-109.12583333    1464.        ] [-109.12555556    1464.        ][-109.12527778    1464.        ]
 [-109.125         1464.        ][-109.12472222    1465.        ][-109.12444444    1465.        ][-109.12416667    1463.        ]
 [-109.12388889    1462.        ][-109.12361111    1461.        ][-109.12333333    1459.        ][-109.12305556    1454.        ]]

I tried this:

numpy_array = np.reshape(4, 4, 2)

but it throws:

ValueError: cannot reshape array of size 1 into shape (4,)

like image 236
raceee Avatar asked Jul 24 '26 20:07

raceee


1 Answers

You can make use of numpy.newaxis

import numpy as np

a = np.zeros((16, 2))
b = a[:, :, np.newaxis]
c = b.reshape(4, 4, 2)

print(c.shape)
like image 77
Abhishek S Avatar answered Jul 26 '26 11:07

Abhishek S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!