NumPy – Create NumPy Array


Create NumPy array using different methods. The power of NumPy lies in its array. The array generated via NumPy takes less memory space and process faster than Python Lists.

Syntax of Creating NumPy array

numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0)

NOTE: Only object is compulsory. It may be any object that return an array like list, tuple, function, method.

we have multiple methods to generate a NumPy array in Python.

Numpy Array using Python List

Example-1

import numpy as np
a = np.array([1,2,3,4,5,5,6,7,8])
print(a)

The above example generates an np array using the array( ) method. Code generates the following output when executed.

[1 2 3 4 5 5 6 7 8]

It creates a list like this in the memory along with indexes. Tuple can also be used here for arguments.
create numpy array

Create Numpy Array using arrange method

Example

import numpy as np
a = np.arange(10)
print(a)

Outpu of the above code is

$ python -u "c:\python\numpy\create_1.py"
[0 1 2 3 4 5 6 7 8 9]

NumPy array with NumPy data Type

import numpy as np
a = np.array([0,1,2,3,4,5,6,7,78],dtype=np.int16)
print(a)

Numpy Array with all zero element

pre>
import numpy as np
a = np.zeros(10,dtyle=bool)
print(a

NumPy Array with all element as 1

import numpy as np
a = np.ones(10,dtype=bool)
print(a)

NumPy Array with Boolean Data Type

import numpy as np
a =np.arrays([10,5,06,3,23,1,2,0,1,1,0],dtype=bool)
print(a)

These are a few ways to generate a NumPy array of a single dimension. ndim parameter is used to define a 2-D or 3-D array.

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.