Arrays in Python: NumPy Arrays

NumPy arrays are designed for efficient numerical computations, especially large arrays. NumPy is the foundation for scientific computing in Python (used by SciPy, pandas, scikit-learn, TensorFlow, etc.).

Installing NumPy

Install via pip:

code.python
python -m pip install numpy

NumPy is typically installed in C:\Users\Username\AppData\Local\Programs\Python\Python3x (e.g., Python37 for Python 3.7).

Creating NumPy Arrays

array() Function: Convert lists to arrays.

code.python
>>> class="text-secondary">import numpy class="text-secondary">as np
>>> a = np.array([1, 2, 3])
>>> print(a)  # [1 2 3]

arange(): Create arrays with incremental values (similar to range).

code.python
>>> x = np.arange(5)  # [0 1 2 3 4]
>>> x = np.arange(5, dtype=float)  # [0. 1. 2. 3. 4.]
>>> x = np.arange(10, 0, -2)  # [10 8 6 4 2] (descending)

linspace(): Create evenly spaced arrays (specify number of points).

code.python
>>> x = np.linspace(10, 20, 5)  # [10. 12.5 15. 17.5 20.]
>>> x = np.linspace(10, 20, 5, endpoint=False)  # [10. 12. 14. 16. 18.] (exclude end)

logspace(): Create logarithmically spaced arrays (default base 10).

code.python
>>> x = np.logspace(1, 2, num=10)  # [10. 12.915... 100.]
>>> x = np.logspace(1, 10, num=10, base=2)  # [2. 4. 8. ... 1024.]

fromiter(): Create arrays from iterators.

code.python
>>> lst = range(5)
>>> it = iter(lst)
>>> x = np.fromiter(it, dtype=float)  # [0. 1. 2. 3. 4.]

2D Arrays: Use nested lists.

code.python
>>> c = np.array([[1., 2.], [3., 4.]])
>>> print(c)  # [[1. 2.] [3. 4.]]

Indexing and Slicing

Similar to Python lists, but with additional support for multi-dimensional indexing:

code.python
>>> a = np.arange(8)  # [0 1 2 3 4 5 6 7]
>>> a[2]  # 2(3rd element)
>>> a[2:5]  # [2 3 4] (indices 24)
>>> a[-3:]  # [5 6 7] (last 3 elements)

Calculations with NumPy Arrays

NumPy provides functions for math, statistics, linear algebra, and more:

Math Functions: np.square(a), np.sqrt(a), np.exp(a), np.sin(a), etc.

Statistics: np.max(a), np.mean(a), np.sum(a), np.median(a), np.std(a), np.var(a).

Special Matrices: np.zeros((3, 2)) (3x2 zeros), np.ones((2, 4)) (2x4 ones), np.eye(3) (3x3 identity matrix).

Linear Algebra: np.transpose(a), np.dot(a, b) (dot product), np.linalg.det(a) (determinant), np.linalg.inv(a) (inverse).

Exchanging Data Between Excel and NumPy Arrays

Use xlwings to read/write NumPy arrays:

Write to Excel:

code.python
>>> sht = xw.Book().sheets(1)
>>> sht.range('B2').value = np.array([[1, 2, 3], [4, 5, 6]])

Read from Excel:

code.python
>>> arr = sht.range('B2').options(np.array, expand='table').value
>>> print(arr)  # [[1. 2. 3.] [4. 5. 6.]]