numpy
  1. numpy-array-creation

Array Creation in NumPy

NumPy is a powerful numerical library in Python that provides support for multi-dimensional arrays and matrices. It offers a various set of functions for creating arrays which makes it easy to work on arrays in Python.

Syntax

NumPy provides multiple functions for creating arrays like np.array, np.zeros, np.ones, np.full, np.random.rand and so on. The basic syntax for creating an array using np.array is as follows:

import numpy as np

array = np.array(list, dtype=None, copy=True, order=None, subok=False, ndmin=0)

Here, list is the input data in the form of a list or tuple.

Example

Consider the following example where we will create a 1D and a 2D array using np.array:

import numpy as np

# 1D array
arr1d = np.array([1, 2, 3, 4, 5])
print(arr1d)

# 2D array
arr2d = np.array([[1, 2], [3, 4], [5, 6]])
print(arr2d)

The output of the above code will be:

[1 2 3 4 5]
[[1 2]
 [3 4]
 [5 6]]

Explanation

NumPy provides various functions for creating arrays, out of which np.array is the most basic and commonly used one. We can create an array by passing a list or a tuple into the np.array function, as shown in the example above.

Use

Arrays are used to store and manipulate large amounts of data efficiently. NumPy arrays have many advantages over Python lists, such as faster execution and easier data manipulation.

Important Points

  • NumPy provides many methods for creating arrays like np.zeros, np.ones, np.full, np.empty, np.ndarray, np.random.rand, np.random.randint and so on, each with its own unique feature set.
  • The dtype parameter of the np.array function can be set to specify the datatype of the array.
  • The copy parameter in the np.array function specifies whether to create a new copy of an array or to use an existing one.
  • The order parameter in the np.array function specifies the order in which the array's memory layout is organized.
  • The ndmin parameter in the np.array function specifies the minimum number of dimensions that the resulting array should have.

Summary

NumPy provides multiple functions for creating arrays, and the most commonly used one is np.array. We can create arrays by passing a list or tuple as an argument in the np.array function. Arrays are extensively used in scientific computing and data analysis and are more efficient than Python lists, making it one of the most essential libraries for programmers working with data.

Published on: