NumPy Create Array, numpy.empty(), numpy.zeros(), numpy.ones(), numpy.asarray(), numpy.frombuffer(), numpy.fromiter()

NumPy Create Array

NumPy is a powerful library in Python that supports large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. Here's a tutorial on how to create arrays in NumPy:

Step 1: Importing NumPy

Before you start using NumPy, you need to import it. It is common to import NumPy under the alias np:

import numpy as np 

Step 2: Creating a NumPy Array

The basic way to create a NumPy array is with the np.array() function:

# Create a 1-dimensional array arr = np.array([1, 2, 3]) print(arr) # Output: array([1, 2, 3]) # Create a 2-dimensional array arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) print(arr_2d) # Output: array([[1, 2, 3], [4, 5, 6]]) 

Step 3: Creating Arrays with np.zeros(), np.ones(), and np.empty()

NumPy provides functions to create arrays filled with zeros (np.zeros()), ones (np.ones()), or uninitialized data (np.empty()):

# Create an array of zeros zeros = np.zeros((3, 4)) print(zeros) # Output: # array([[0., 0., 0., 0.], # [0., 0., 0., 0.], # [0., 0., 0., 0.]]) # Create an array of ones ones = np.ones((2, 3)) print(ones) # Output: # array([[1., 1., 1.], # [1., 1., 1.]]) # Create an empty array (the array is filled with random noise) empty = np.empty((3, 3)) print(empty) 

Step 4: Creating Arrays with np.arange() and np.linspace()

np.arange() creates an array with regularly incrementing values, while np.linspace() creates an array with a specified number of evenly spaced intervals between two values:

# Create an array with np.arange() arr_range = np.arange(0, 10, 2) # Start, end (exclusive), step print(arr_range) # Output: array([0, 2, 4, 6, 8]) # Create an array with np.linspace() arr_space = np.linspace(0, 1, 5) # Start, end (inclusive), number of points print(arr_space) # Output: array([0. , 0.25, 0.5 , 0.75, 1. ]) 

Step 5: Creating Identity Matrix with np.eye()

An identity matrix is a square matrix with ones on the main diagonal. You can create it with np.eye():

# Create an identity matrix identity = np.eye(3) print(identity) # Output: # array([[1., 0., 0.], # [0., 1., 0.], # [0., 0., 1.]]) 

These are some of the ways to create arrays in NumPy. There are more advanced methods available, which you can discover by exploring the NumPy documentation.


More Tags

ieee-754 resteasy websocket hook-woocommerce uialertview .net-6.0 bitset onblur pikepdf tr

More Programming Guides

Other Guides

More Programming Examples