Instagram
youtube
Facebook
Twitter

Creating Numpy Arrays

Numpy is a very important library when working with numerical data in Python. NumPy is a powerful library for numerical and scientific computing, and it also provides support for working with arrays, matrices, and a wide range of mathematical operations.

In this tutorial, we'll learn about various methods used for creating NumPy arrays.

Creating Arrays from Python Lists

The most common and easy method to create NumPy arrays is by converting Python lists into arrays. We can create arrays from lists using the numpy.array() function.

Example

import numpy as np
arr = np.array([1,2,3,4,5])
print(arr)
print(type(arr))

Output

[1 2 3 4 5]
<class 'numpy.ndarray'>

 

Creating Arrays with initial values

We can create arrays with initial values like (0, 1 etc.) using functions like numpy.zeros(), numpy.ones(), and numpy.full()

Example

import numpy as np
arr = np.zeros(5) #Creating 1D array of 0's
print(arr)

arr1 = np.ones((3,4)) #Creating 2D array of 1's
print(arr1)

arr2 = np.full((3,4),5) #Creating 2D array of 5's (Custom array)
print(arr2)

Output

[0. 0. 0. 0. 0.]

[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

[[5 5 5 5]
 [5 5 5 5]
 [5 5 5 5]]

 

Creating Arrays with Ranges

We can create arrays with sequences of numbers using functions like numpy.arange(), numpy.linspace(), and numpy.logspace().

  • numpy.arange(start, stop, step): It is used to generate a 1D array with evenly spaced values from start to stop - 1 using the specified step size.

  • numpy.linspace(start, stop, num): It create's a 1D array with num evenly spaced values between start and stop (inclusive).

  • numpy.logspace(start, stop, num, base): It create's a 1D array with num logarithmically spaced values between base**start and base**stop (inclusive).

 

Example

import numpy as np
arr = np.arange(10)
arr1 = np.linspace(0, 1, 5)
arr2 = np.logspace(0, 1, 5)
print(arr)
print(arr1)
print(arr2)

Output

[0 1 2 3 4 5 6 7 8 9]
[0.   0.25 0.5  0.75 1.  ]
[ 1.          1.77827941  3.16227766  5.62341325 10.        ]