NumPy array()
NumPy's array()
function is a powerful method for creating arrays from Python data structures. It allows for efficient storage and manipulation of numerical data, making it essential for scientific and mathematical computing.
Usage
The np.array()
function is used to convert Python lists, tuples, other array-like objects such as existing NumPy arrays, or any similar structures into NumPy arrays. This is crucial for performing vectorized operations and leveraging NumPy's optimized routines.
numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0)
object
: The array-like input data.dtype
: Desired data type of the array (e.g.,int
,float
).copy
: IfTrue
, the object is copied.order
: Memory layout order ('C'
for row-major,'F'
for column-major,'A'
to preserve input order as much as possible,'K'
for default order).subok
: IfFalse
, the returned array is a base class array; ifTrue
, subclasses are passed through.ndmin
: Minimum number of dimensions required.
Examples
1. Basic Array Creation
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
This example creates a one-dimensional NumPy array from a Python list containing integers.
2. Multi-dimensional Array
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
Here, a two-dimensional array is created from a nested list, effectively forming a matrix.
3. Array with Specified Data Type
import numpy as np
arr = np.array([1.5, 2.5, 3.5], dtype=np.int32)
This example creates a one-dimensional array with specified data type int32
, converting all floating-point numbers to integers.
4. Using `ndmin` to Add Dimensions
import numpy as np
arr = np.array([1, 2, 3], ndmin=2)
This creates a two-dimensional array from a one-dimensional list, adding an extra dimension automatically.
5. Combining Parameters for Array Creation
import numpy as np
arr = np.array([[1, 2], [3, 4]], dtype=np.float64, order='F')
This creates a two-dimensional array with specified data type float64
and column-major memory layout.
Tips and Best Practices
When using np.array()
, consider specifying the dtype
to ensure consistency and save memory, especially with large datasets. If a specific number of dimensions is needed, use ndmin
to add extra dimensions automatically. By default, np.array()
creates a copy of the input data; use copy=False
if a duplicate is unnecessary. Leverage broadcasting for efficient operations on arrays of different shapes; for example, adding a scalar to an array. Optimize performance by choosing the appropriate order
parameter ('C'
, 'F'
, 'A'
, or 'K'
) based on your use case.