What are array formulas and how do you use them in python
In Python, the equivalent of array formulas (like in Excel or Google Sheets) is typically done using NumPy, a powerful library for numerical computing.
What Are "Array Formulas" in Python?
Array formulas perform operations on entire arrays (lists or matrices) at once, rather than looping through individual elements.
In Python, this is commonly handled using NumPy arrays.
Using NumPy for Array Operations
First, install NumPy (if not already):
bash
CopyEdit
pip install numpy
Then in Python:
python
CopyEdit
import numpy as np # Create two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Add arrays (element-wise) c = a + b print(c) # Output: [5 7 9] # Multiply arrays (element-wise) d = a * b print(d) # Output: [4 10 18]
Common Array Operations (Formulas)
| Operation | Python Code | Description |
|---|---|---|
| Sum | np.sum(arr) |
Sum of all elements |
| Mean | np.mean(arr) |
Average of elements |
| Element-wise Add | a + b |
Adds each corresponding element |
| Dot Product | np.dot(a, b) |
Matrix or vector multiplication |
| Conditional | arr[arr > 10] |
Filter elements greater than 10
|