Understanding Array Basics
What is an Array?
An array is a fundamental data structure in Python used to store multiple elements of the same type in a contiguous memory location. In Python, we typically use NumPy arrays for efficient numerical computations.
Creating Arrays in Python
Basic Array Creation
import numpy as np
## Creating a 1D array
simple_array = np.array([1, 2, 3, 4, 5])
## Creating a 2D array
matrix_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Array Generation Methods
graph LR
A[Array Creation Methods] --> B[np.zeros]
A --> C[np.ones]
A --> D[np.arange]
A --> E[np.linspace]
Here are different ways to generate arrays:
## Create an array of zeros
zero_array = np.zeros((3, 4)) ## 3x4 array of zeros
## Create an array of ones
one_array = np.ones((2, 3)) ## 2x3 array of ones
## Create an array with a range of values
range_array = np.arange(0, 10, 2) ## 0 to 10, step 2
## Create an array with evenly spaced values
linear_array = np.linspace(0, 1, 5) ## 5 evenly spaced values between 0 and 1
Array Attributes
Attribute |
Description |
Example |
shape |
Returns dimensions of the array |
array.shape |
dtype |
Returns data type of array elements |
array.dtype |
size |
Total number of elements |
array.size |
ndim |
Number of dimensions |
array.ndim |
Basic Array Operations
## Element-wise operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
## Addition
result_add = a + b ## [5, 7, 9]
## Multiplication
result_mult = a * b ## [4, 10, 18]
## Scalar operations
scalar_mult = a * 2 ## [2, 4, 6]
Memory Efficiency
NumPy arrays are more memory-efficient and faster than standard Python lists for numerical computations. They provide a powerful tool for scientific computing and data analysis.
Key Takeaways
- Arrays are fundamental for numerical computing in Python
- NumPy provides versatile array creation and manipulation methods
- Arrays support efficient mathematical operations
- Understanding array basics is crucial for data analysis with LabEx tools