What is numpy?
- NumPy is an open source project that enables numerical computing with Python. Numpy is implemented in C, its performance is faster than a Python list.
- Document
Core Features
- ndarray: N-dimensional Array Object, the basic data type of NumPy.
- Vectorization: Operations (or Calculations) performed on the entire array without explicit loops.
- Broadcasting: Enables operations between arrays of different shapes (or sizes)
Array Operations and Attributes
1. Array Creation
- np.array(): Creates an array from a Python list.
- np.zeros(): An array filled with zeros.
- np.ones(): An array filled with ones.
- np.arange(): An array of consecutive numbers.
- np.linspace(): An array with evenly spaced numbers.
- np.random: Module for generating random arrays.
2. Array Attributes
- shape: The array's dimensions/axes (rows, columns).
- dtype: Data type.
- ndim: Number of dimensions.
- size: Total number of elements.
3. Array Indexing and Slicing
- Basic Indexing: arr[0], arr[1, 2]
- Slicing: arr[1:3], arr[:, 1:]
- Boolean Indexing: arr[arr > 5]
- Fancy Indexing: arr[[1, 3, 5]]
- Allows selection of non-contiguous (non-sequential) elements at once.
- Enables extraction of elements based on indices that meet specific criteria.
- Highly useful for data rearrangement and sampling.
4 .Reshaping Arrays
- reshape(): Changes the shape of an array.
- flatten(): Flattens the array to one dimension (1D).
- transpose(): Transposes the array.
5. Broadcasting
Rules that enable operations between arrays of different shapes:
- If the number of dimensions differs, a 1 is prepended to the shape of the smaller array.
- In any dimension where the size is 1, the array is stretched to match the size of the other array.
- An error occurs if the sizes are different and neither is 1.
6. Array Joining and Splitting
- np.concatenate(): Joins arrays.
- np.vstack(), np.hstack(): Stacks arrays vertically and horizontally, respectively.
- np.split(): Splits the array.
Performance Tips
- Use vectorized operations (instead of Python loops).
- Select an appropriate data type
- Avoid unnecessary array copies
- Perform conditional operations using np.where().
Comments
Post a Comment