ValueError: all input arrays must have the same number of dimensions

I have a problem with np.append.

I am trying to duplicate the last column of a 20x361 matrix n_list_convertedusing the following code:

n_last = []
n_last = n_list_converted[:, -1]
n_lists = np.append(n_list_converted, n_last, axis=1)

But I get the error:

ValueError: all input arrays must have the same number of dimensions

However, I checked the dimensions of the matrix by doing

 print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted))

and i get

(20L,) (20L, 361L)

to fit the size? Where is the mistake?

+14
source share
4 answers

If I start with a 3x4 array and concatenate a 3x1 array, with axis 1, I get a 3x5 array:

In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))

Note that both concatenation inputs have 2 dimensions.

Omit :, and x[:,-1]- form (3) is 1d and therefore the error:

In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions

np.append ( , )

return concatenate((arr, values), axis=axis)

, append . 2 . append , .

In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

np.hstack , atleast_1d, :

return np.concatenate([np.atleast_1d(a) for a in arrs], 1)

x[:,-1:]. , .

np.column_stack 1. 1d

array(arr, copy=False, subok=True, ndmin=2).T

(3) (3,1).

In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]: 
array([[ 3],
       [ 7],
       [11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

"" , np.concatenate. , . ipython ??.

np.concatenate - , , .

+12

(n,) (n, 1) . [:, None]:

n_lists = np.append(n_list_converted, n_last[:, None], axis=1)

n_last

n_last = n_list_converted[:, -1:]

(20, 1).

+8

, , , "1 n" n.

hstack() vstack(). :

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

"7, 15, 23, 31". , a[:,-1] a[:,-1:]. :

array([[7],
       [15],
       [23],
       [31]])

array([7,15,23,31])


: append() . .

+5

(n,) (n, 1), [].

, np.append(b,a,axis=0) np.append(b,[a],axis=0)

a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)

array([[5, 6],
       [7, 8],
       [1, 2]])
0

Source: https://habr.com/ru/post/1650654/


All Articles