Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numpy array manipulations

I need to somehow make that array:

[[639 190]
 [ 44   1]
 [ 71   4]
 ...,
 [863 347]
 [870 362]
 [831 359]]

look like this:

[[[639 190]]
 [[ 44   1]]
 [[ 71   4]]
 ...,
 [[863 347]]
 [[870 362]]
 [[831 359]]]

How would I do that? I'm new to numpy and I need it for my scientific experiment.

like image 302
AnatoliySultanov Avatar asked Apr 08 '26 22:04

AnatoliySultanov


2 Answers

Add a new axis with None/np.newaxis -

a[:,None,:] # Or simply a[:,None]

Sample run -

In [222]: a = np.random.randint(0,9,(4,3))

In [223]: a
Out[223]: 
array([[1, 6, 6],
       [4, 4, 5],
       [7, 4, 4],
       [4, 1, 3]])

In [224]: a[:,None]
Out[224]: 
array([[[1, 6, 6]],

       [[4, 4, 5]],

       [[7, 4, 4]],

       [[4, 1, 3]]])
like image 128
Divakar Avatar answered Apr 10 '26 11:04

Divakar


In addition to newaxis/None mentioned by @Divakar,

np.expand_dims(input_array, axis=1)
like image 42
AGN Gazer Avatar answered Apr 10 '26 12:04

AGN Gazer



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!