Okay, let's put the concepts from this chapter into practice. Theory is helpful, but working directly with the code solidifies understanding. We'll create several NumPy arrays using different methods discussed and then use the inspection attributes to understand their structure.
First, ensure you have NumPy installed and import it. The standard convention is to import it under the alias np
. If you are working in a Jupyter Notebook or an interactive Python environment, execute this line:
import numpy as np
The most straightforward way to create a NumPy array is from an existing Python list or tuple.
1. One-Dimensional Array: Let's start with a simple list of integers.
# Create a Python list
list_1d = [1, 3, 5, 7, 9]
# Create a NumPy array from the list
array_1d = np.array(list_1d)
# Print the array
print(array_1d)
Output:
[1 3 5 7 9]
Now, let's inspect its properties:
print(f"Type: {type(array_1d)}")
print(f"Data Type (dtype): {array_1d.dtype}")
print(f"Dimensions (ndim): {array_1d.ndim}")
print(f"Shape: {array_1d.shape}")
print(f"Size: {array_1d.size}")
Output:
Type: <class 'numpy.ndarray'>
Data Type (dtype): int64
Dimensions (ndim): 1
Shape: (5,)
Size: 5
Notice NumPy inferred the data type as int64
(a 64-bit integer, the default integer type often depends on your system). It's a 1-dimensional array (ndim=1
) with 5 elements (size=5
), and its shape is represented as (5,)
, indicating 5 elements along the single axis.
2. Two-Dimensional Array: Now, let's use a nested list to create a 2D array (like a matrix).
# Create a nested Python list
list_2d = [[1, 2, 3], [4, 5, 6]]
# Create a 2D NumPy array
array_2d = np.array(list_2d)
# Print the array
print(array_2d)
Output:
[[1 2 3]
[4 5 6]]
Let's inspect this 2D array:
print(f"Data Type (dtype): {array_2d.dtype}")
print(f"Dimensions (ndim): {array_2d.ndim}")
print(f"Shape: {array_2d.shape}")
print(f"Size: {array_2d.size}")
Output:
Data Type (dtype): int64
Dimensions (ndim): 2
Shape: (2, 3)
Size: 6
This time, NumPy correctly identified it as a 2-dimensional array (ndim=2
). The shape (2, 3)
tells us it has 2 rows and 3 columns. The total number of elements (size
) is 2×3=6.
NumPy provides functions to create arrays without starting from Python lists, which is often more efficient.
1. np.zeros
and np.ones
:
These functions create arrays filled with zeros or ones, respectively. You need to provide the desired shape as a tuple.
# Create a 3x4 array filled with zeros
zeros_array = np.zeros((3, 4))
print("Zeros Array:\n", zeros_array)
print(f"Zeros dtype: {zeros_array.dtype}\n") # Default is float64
# Create a 1D array of 5 ones, specifying integer type
ones_array = np.ones(5, dtype=np.int16)
print("Ones Array:\n", ones_array)
print(f"Ones dtype: {ones_array.dtype}")
print(f"Ones shape: {ones_array.shape}")
Output:
Zeros Array:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
Zeros dtype: float64
Ones Array:
[1 1 1 1 1]
Ones dtype: int16
Ones shape: (5,)
Note how np.zeros
defaults to floating-point numbers (float64
), while we explicitly requested 16-bit integers (int16
) for np.ones
.
2. np.arange
:
Similar to Python's range
, but returns a NumPy array.
# Create an array with values from 0 up to (but not including) 10, step 2
range_array = np.arange(0, 10, 2)
print("Arange Array:\n", range_array)
print(f"Arange shape: {range_array.shape}")
print(f"Arange dtype: {range_array.dtype}")
Output:
Arange Array:
[0 2 4 6 8]
Arange shape: (5,)
Arange dtype: int64
3. np.linspace
:
Creates an array with a specified number of elements, evenly spaced between a start and end value (inclusive).
# Create an array of 6 evenly spaced values between 0 and 1 (inclusive)
linspace_array = np.linspace(0, 1, 6)
print("Linspace Array:\n", linspace_array)
print(f"Linspace shape: {linspace_array.shape}")
print(f"Linspace dtype: {linspace_array.dtype}")
Output:
Linspace Array:
[0. 0.2 0.4 0.6 0.8 1. ]
Linspace shape: (6,)
Linspace dtype: float64
NumPy arrays are efficient because all elements typically share the same data type. Let's see what happens when we create arrays and specify types.
# Create an array from a list containing floats
float_array = np.array([1.0, 2.5, 3.7, 4.2])
print("Float Array:", float_array)
print(f"dtype: {float_array.dtype}\n")
# Explicitly specify integer type (truncation occurs)
int_from_float = np.array([1.0, 2.5, 3.7, 4.2], dtype=np.int32)
print("Int from Float Array:", int_from_float)
print(f"dtype: {int_from_float.dtype}\n")
# Create from mixed list (NumPy upcasts to compatible type)
mixed_array = np.array([1, 2.5, 3, 4.8])
print("Mixed Array:", mixed_array)
print(f"dtype: {mixed_array.dtype}")
Output:
Float Array: [1. 2.5 3.7 4.2]
dtype: float64
Int from Float Array: [1 2 3 4]
dtype: int32
Mixed Array: [1. 2.5 3. 4.8]
dtype: float64
When we forced the floats into an int32
array, the decimal parts were truncated. When creating an array from a mixed list of integers and floats without specifying a dtype
, NumPy intelligently upcasts all elements to float64
to accommodate the floating-point numbers without losing information.
Sometimes a visual representation helps understand the structure, especially for 2D arrays. Let's visualize the array_2d
we created earlier ([[1,2,3],[4,5,6]]) which has a shape of (2, 3)
.
The heatmap visually represents the 2 rows and 3 columns of
array_2d
. Each cell corresponds to an element in the array, showing its value and position.
This practical session covered creating NumPy arrays from lists and using specialized functions like np.zeros
, np.ones
, np.arange
, and np.linspace
. We also practiced inspecting fundamental array attributes: dtype
, ndim
, shape
, and size
. Understanding these creation methods and attributes is foundational for effectively using NumPy for numerical tasks. You are now equipped to create the basic building blocks for data analysis and scientific computing in Python.
© 2025 ApX Machine Learning