How to build ndarray from a numpy array? python

I cannot convert it to ndarray to numpy, I read http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html , but it doesn’t show me how I can convert my input, as shown below in ndarray .

How to build ndarray from numpy array or list of whole lists? * What is the difference between ndarray and array? * Could I just use the array type correctly?

I have a list of integers like this

 [[1, 2, 4, 1, 5], [6, 0, 0, 0, 2], [0, 0, 0, 1, 0]] 

And I manage to use this code to create np.array , as shown in http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array

 import numpy as np x = [[1, 2, 4, 1, 5], [6, 0, 0, 0, 2], [0, 0, 0, 1, 0]] print np.array(x) 

[output]:

 [[1 2 4 1 5] [6 0 0 0 2] [0 0 0 1 0]] 

But I can not change it to np.ndarray with this code:

 import numpy as np x = [[1, 2, 4, 1, 5], [6, 0, 0, 0, 2], [0, 0, 0, 1, 0]] print np.ndarray(x) 

There was an error:

 Traceback (most recent call last): File "/home/alvas/workspace/sklearntut/test.py", line 7, in <module> print np.ndarray(x) TypeError: an integer is required 

How to create np.ndarray with a list of integers that I have? What integer is talking about TypeError?

+6
source share
2 answers

An ndarray - an array of NumPy.

 >>> x = np.array([1, 2, 3]) >>> type(x) <type 'numpy.ndarray'> 

The difference between np.ndarray and np.array is that the former is the actual type, and the latter is a flexible shorthand function for building arrays from data in other formats. TypeError uses the arguments np.array for np.ndarray , which takes completely different arguments (see Docstrings).

+24
source

Although the accepted answer is correct, this did not help me create a 1-dimensional array of arrays.

Since this thread is the first answer on Google, I am posting my work, even if it is not an elegant solution (please feel free to point to me):

 import numpy as np # Create example array initial_array = np.ones(shape = (2,2)) # Create array of arrays array_of_arrays = np.ndarray(shape = (1,), dtype = "object") array_of_arrays[0] = initial_array 

Remember that array_of_arrays in this case is changed, i.e. changing initial_array automatically changes array_of_arrays .

+3
source

All Articles