Home > database >  how to reshape 3D to 2D ? but I don't want to lose the brackets in between?
how to reshape 3D to 2D ? but I don't want to lose the brackets in between?

Time:09-26

I have this array

X = np.array([[-2, -1.9], [-3, -2], [-1, -1],  [1, 1.5], [3, 2]])

once I insert a point

x = np.asarray([[204.9]]) 

it becomes 3D

array([[[-2. , -1.9],
        [-3. , -2. ],
        [-1. , -1. ],
        [ 1. ,  1.5],
        [ 3. ,  2. ],
        [20. ,  4.9]]])

How to keep it always 2D even if I added points ?

CodePudding user response:

np.concatenate((X, x), axis=0)

result:

array([[-2. , -1.9],
       [-3. , -2. ],
       [-1. , -1. ],
       [ 1. ,  1.5],
       [ 3. ,  2. ],
       [20. ,  4.9]])

CodePudding user response:

Try this:

>>> X = np.array([[-2, -1.9], [-3, -2], [-1, -1],  [1, 1.5], [3, 2]])
>>> x = np.asarray([[20, 4.9]]) 
>>> np.append(X,x,axis=0)
array([[-2. , -1.9],
       [-3. , -2. ],
       [-1. , -1. ],
       [ 1. ,  1.5],
       [ 3. ,  2. ],
       [20. ,  4.9]])
>>> np.insert(X, len(X), x, axis=0)
array([[-2. , -1.9],
       [-3. , -2. ],
       [-1. , -1. ],
       [ 1. ,  1.5],
       [ 3. ,  2. ],
       [20. ,  4.9]])

Edit answer base your comment: (Change 3D numpy.array to 2D numpy.array)

>>> Y = np.array([[[-2. , -1.9], [-3. , -2. ], [-1. , -1. ], [ 1. , 1.5], [ 3. , 2. ], [20. , 4.9]]])
>>> Y.shape
(1, 6, 2)

>>> Z = Y.reshape(Y.shape[1],Y.shape[2])
>>> Z.shape
(6, 2)

Update: (get numpy.array elements with another list)

>>> X = np.array([[-2, -1.9], [-3, -2], [-1, -1],  [1, 1.5], [3, 2]])
>>> ex = [0,1,0,1] 
>>> X[np.array(ex)]
array([[-2. , -1.9],
       [-3. , -2. ],
       [-2. , -1.9],
       [-3. , -2. ]])
  • Related