NumPy Creating Arrays
This lesson covers np.array() and how NumPy represents data at every dimension, from a single scalar (0-D) up to arrays with many axes (n-D).
Creating Arrays with np.array()
The np.array() function is the most direct way to build an ndarray: pass it a Python list (or a list of lists), and NumPy converts it into an array, picking an appropriate dtype automatically.
Creating a Basic Array
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr) # [10 20 30 40]
print(type(arr)) # <class 'numpy.ndarray'>Dimensions: 0-D, 1-D, 2-D, and n-D
NumPy arrays can have any number of dimensions, referred to as axes. A 0-D array is a single scalar value with no axes. A 1-D array is a flat list of values (one axis). A 2-D array is a table of rows and columns (two axes), and anything with three or more axes is simply called n-dimensional. The ndim attribute tells you how many axes an array has, and shape tells you the size along each axis.
- 0-D array: a single number, e.g. np.array(42) - ndim is 0
- 1-D array: a flat sequence, e.g. np.array([1, 2, 3]) - ndim is 1
- 2-D array: rows and columns, e.g. np.array([[1, 2], [3, 4]]) - ndim is 2
- 3-D array: a stack of 2-D arrays, e.g. np.array([[[1,2],[3,4]], [[5,6],[7,8]]]) - ndim is 3
- n-D array: pass the ndmin argument to force extra dimensions, e.g. np.array([1, 2, 3], ndmin=5)
Arrays at Every Dimension
import numpy as np
scalar = np.array(42)
vector = np.array([1, 2, 3])
matrix = np.array([[1, 2, 3], [4, 5, 6]])
tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for name, a in [('scalar', scalar), ('vector', vector), ('matrix', matrix), ('tensor', tensor)]:
print(name, '-> ndim:', a.ndim, 'shape:', a.shape)Forcing Extra Dimensions with ndmin
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape:', arr.shape) # (1, 1, 1, 1, 4)
print('ndim:', arr.ndim) # 5Exercise: NumPy Creating Arrays
Which function is used to create a NumPy array from a Python list?