In this tutorial, you will learn how to create NumPy arrays, including one-dimensional, two-dimensional, and three-dimensional arrays, and explore their properties.
Introduction
A NumPy array is the core data structure provided by the NumPy library. It represents a grid of values, all of the same type, indexed by a tuple of non-negative integers. All NumPy arrays are instances of the ndarray class and can be created using the array() function.
Creating One-Dimensional Arrays
To create a 1D array, pass a Python list to the np.array() function:
import numpy as np
a = np.array([1, 2, 3])
print(type(a))
print(a)
Output:
<class 'numpy.ndarray'>
[1 2 3]
This creates a 1D NumPy array (also known as a vector).
Getting the Dimension of an Array
Use the ndim property to get the number of dimensions (axes):
print(a.ndim) # Output: 1
Getting the Data Type of Array Elements
Use the dtype property to get the data type of array elements:
print(a.dtype) # Output: int32 (may vary based on system)
You can explicitly set the data type using the dtype argument:
a = np.array([1, 2, 3], dtype=np.float64)
print(a)
print(a.dtype)
Output:
[1. 2. 3.]
float64
Creating Two-Dimensional Arrays
A 2D array (matrix) is created by passing a list of lists:
b = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(b)
print(b.ndim)
Output:
[[1 2 3]
[4 5 6]]
2
Creating Three-Dimensional Arrays
A 3D array (tensor) is created by nesting lists within lists:
c = np.array([
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9],
[10, 11, 12]
]
])
print(c.ndim) # Output: 3
Getting the Shape of Arrays
Use the shape property to find the number of axes and the number of elements along each axis:
a = np.array([1, 2, 3])
print(a.shape) # (3,)
b = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(b.shape) # (2, 3)
c = np.array([
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9],
[10, 11, 12]
]
])
print(c.shape) # (2, 2, 3)
The shape property returns a tuple:
-
The number of elements in the tuple is the number of dimensions (axes).
-
Each element represents the size along that dimension.
Summary
-
A NumPy array is a grid of values with the same data type.
-
Arrays are instances of the
ndarrayclass and are created usingnp.array(). -
Use
ndimto get the number of dimensions. -
Use
dtypeto check or specify the data type of elements. -
Use
shapeto determine the structure of the array in terms of axes and elements per axis.
Copyright statement: Unless otherwise indicated, all articles are original to this site, please cite the source when sharing.
Article link:http://pybeginners.com/numpy/how-to-create-a-numpy-arrays/
License agreement:Creative Commons Attribution-NonCommercial 4.0 International License