Numpy Basic Flashcards

1
Q

How do you import NumPy under the common alias np and create a 1D array from the Python list [1, 2, 3]?

A

```python
import numpy as np
arr = np.array([1, 2, 3])
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you check the shape of a NumPy array arr = np.array([[1, 2], [3, 4]])?

A

```python
arr.shape # Returns (2, 2)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Given arr = np.array([1, 2, 3, 4]), how do you reshape it into a 2x2 matrix?

A

```python
matrix = arr.reshape((2, 2))
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you create a NumPy array of 5 evenly spaced numbers between 0 and 1 (inclusive)?

A

```python
arr = np.linspace(0, 1, 5)
# [0. 0.25 0.5 0.75 1. ]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you create a NumPy array of numbers from 0 (inclusive) to 10 (exclusive) in steps of 2?

A

```python
arr = np.arange(0, 10, 2)
# [0 2 4 6 8]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you create a 3x3 NumPy array of all zeros?

A

```python
zeros_3x3 = np.zeros((3, 3))
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you create a 2x2 NumPy array of all ones with a float data type?

A

```python
ones_2x2 = np.ones((2, 2), dtype=float)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you create a 3x3 NumPy identity matrix (1s on the diagonal, 0s elsewhere)?

A

```python
eye_3x3 = np.eye(3)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you select the element at row 1, column 2 of arr = np.array([[10, 20, 30], [40, 50, 60]])?

A

```python
element = arr[1, 2] # 60
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you slice out the first two columns from arr = np.array([[1, 2, 3], [4, 5, 6]]), resulting in [[1, 2], [4, 5]]?

A

```python
slice_2_columns = arr[:, :2]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you slice out the first row only from arr = np.array([[1, 2, 3], [4, 5, 6]])?

A

```python
first_row = arr[0, :]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you slice out just the second row, first two columns from arr = np.array([[1, 2, 3], [4, 5, 6]]), resulting in [4, 5]?

A

```python
slice_part = arr[1, :2]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you change the shape of arr = np.array([1, 2, 3, 4, 5, 6]) into a 2D array with 2 rows and 3 columns, without creating a copy?

A

```python
arr.shape = (2, 3)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you create a random NumPy array of shape (2, 2) using np.random.rand() with values between 0 and 1?

A

```python
arr = np.random.rand(2, 2)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you create a random NumPy array of integers between 0 and 9 (inclusive) of shape (3, 3) using np.random.randint()?

A

```python
arr = np.random.randint(0, 10, (3, 3))
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you get the number of dimensions of arr = np.array([[1, 2], [3, 4]])?

A

```python
arr.ndim # Returns 2
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you compute the sum of all elements in a 2D array arr = np.array([[1, 2], [3, 4]]) using a single NumPy method?

A

```python
total = arr.sum() # 10
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you compute the mean of all elements in the array arr = np.array([1, 2, 3, 4])?

A

```python
mean_val = arr.mean() # 2.5
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you compute the standard deviation of the elements in arr = np.array([1, 2, 3, 4])?

A

```python
std_val = arr.std() # 1.1180…
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Given arr = np.array([[1, 2], [3, 4]]), how do you compute the sum along the rows (axis=1), resulting in [3, 7]?

A

```python
row_sums = arr.sum(axis=1)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you flatten the 2D array arr = np.array([[1, 2], [3, 4]]) into a 1D array without creating a copy (if possible)?

A

```python
flattened_view = arr.ravel()
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you create a copy of arr = np.array([1, 2, 3]) named arr_copy so that changes to arr_copy won’t affect arr?

A

```python
arr_copy = arr.copy()
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you replace all elements in arr = np.array([1, 2, 3, 4]) that are less than 3 with the value 0 (in-place)?

A

```python
arr[arr < 3] = 0
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you extract all elements greater than 2 from arr = np.array([1, 2, 3, 4, 5]) as a new array?

A

```python
filtered = arr[arr > 2]
# [3, 4, 5]
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do you compute the element-wise product of `a = np.array([1, 2, 3])` and `b = np.array([4, 5, 6])`, resulting in `[4, 10, 18]`?
```python product = a * b ```
26
How do you perform matrix multiplication of two 2D arrays `A` (shape 2x2) and `B` (shape 2x2) using NumPy’s recommended operator?
```python result = A @ B # or np.matmul(A, B) ```
27
Given `arr = np.array([3, 1, 2])`, how do you return a sorted copy without modifying `arr`?
```python sorted_arr = np.sort(arr) ```
28
How do you sort the array `arr = np.array([3, 1, 2])` in-place, changing its contents?
```python arr.sort() ```
29
Given a 2D array `arr = np.array([[3, 1], [2, 4]])`, how do you sort each row in ascending order using an axis argument?
```python arr.sort(axis=1) ```
30
How do you find the indices of all elements in `arr = np.array([10, 20, 30, 20])` that are equal to 20?
```python indices = np.where(arr == 20) # indices is (array([1, 3]),) ```
31
How do you use `np.where` to replace all negative numbers in `arr` with 0, leaving positive numbers unchanged?
```python arr = np.array([-1, 2, -3, 4]) arr = np.where(arr < 0, 0, arr) ```
32
How do you concatenate two 1D arrays `x = np.array([1, 2])` and `y = np.array([3, 4])` along the default axis (result `[1, 2, 3, 4]`)?
```python combined = np.concatenate((x, y)) ```
33
How do you stack two 1D arrays `x = np.array([1, 2])` and `y = np.array([3, 4])` vertically, resulting in a 2x2 array?
```python stacked = np.vstack((x, y)) # [[1, 2], # [3, 4]] ```
34
How do you stack two 1D arrays horizontally, given `x = np.array([1, 2])` and `y = np.array([3, 4])`, resulting in a 1x4 array `[1, 2, 3, 4]`?
```python stacked = np.hstack((x, y)) ```
35
How do you split a 1D array `arr = np.array([1, 2, 3, 4, 5, 6])` into three subarrays `[1,2]`, `[3,4]`, `[5,6]` using `np.split()`?
```python sub_arrays = np.split(arr, 3) ```
36
How do you find the minimum value in `arr = np.array([[3, 1], [2, 4]])` across the entire 2D array (not axis-specific)?
```python min_val = arr.min() ```
37
How do you find the maximum value of each column in `arr = np.array([[3, 1], [2, 4]])` using `axis=0`?
```python max_in_cols = arr.max(axis=0) # [3, 4] ```
38
Given `arr = np.array([10, 20, 30, 40])`, how do you compute the cumulative sum, resulting in `[10, 30, 60, 100]`?
```python cumsum_arr = np.cumsum(arr) ```
39
How do you compute the unique elements of `arr = np.array([1, 2, 2, 3, 3, 3])` using a NumPy function, resulting in `[1, 2, 3]`?
```python unique_vals = np.unique(arr) ```
40
How do you generate a random float between 0 and 1 for each element in a 2D shape of `(2,3)` using NumPy’s `np.random.random()`?
```python arr = np.random.random((2, 3)) ```
41
How do you find both the unique elements and their counts in `arr = np.array([1, 2, 2, 3])` using a single NumPy function?
```python unique_vals, counts = np.unique(arr, return_counts=True) ```
42
How do you convert all elements of `arr = np.array([1.5, 2.7, 3.1])` to integers using a NumPy casting function?
```python int_arr = arr.astype(int) ```
43
How do you change the data type of `arr = np.array([1, 2, 3])` from int to float in-place?
```python arr = arr.astype(float, copy=False) ```
44
How do you create a 1D array of booleans indicating which elements of `arr = np.array([1, 3, 2, 5])` are even (`[False, False, True, False]`)?
```python bool_arr = (arr % 2 == 0) ```
45
How do you find the index of the maximum value in `arr = np.array([10, 20, 15])` using a single function call?
```python max_index = np.argmax(arr) # 1 (since arr[1] = 20) ```
46
How do you create a diagonal matrix from a 1D array `arr = np.array([1, 2, 3])`, resulting in [[1,0,0], [0,2,0], [0,0,3]]?
```python diag_matrix = np.diag(arr) ```
47
How do you repeat the array `arr = np.array([1, 2])` 3 times along the row axis, resulting in `[[1,2],[1,2],[1,2]]` using a single function?
```python repeated = np.tile(arr, (3, 1)) ```
48
How do you perform element-wise exponentiation of `arr = np.array([1, 2, 3])` by 2 (squaring), resulting in `[1, 4, 9]`?
```python squared = arr ** 2 # or np.square(arr) ```
49
How do you broadcast and add a 1D array `[1, 2, 3]` to every row of a 2D array `A` with shape `(2, 3)`?
```python A = np.array([[10, 20, 30], [40, 50, 60]]) b = np.array([1, 2, 3]) result = A + b # Broadcasting ```
50
How do you convert a NumPy array `arr = np.array([[1, 2], [3, 4]])` to a Python list of lists?
```python list_of_lists = arr.tolist() ```
51
How do you create a NumPy array of shape (3, 1) filled with the value 7 using `np.full`?
```python import numpy as np arr = np.full((3, 1), 7) # [[7], # [7], # [7]] ```
52
How do you clip all values in `arr = np.array([1, 5, 10, 15])` to lie between 3 and 12?
```python clipped = np.clip(arr, 3, 12) # [ 3 5 10 12] ```
53
How do you create a NumPy array `arr` such that it has a shape (2, 3, 4) filled with zeros, then reshape it to (2, 12)?
```python arr = np.zeros((2, 3, 4)) arr_reshaped = arr.reshape((2, 12)) ```
54
How do you horizontally stack two 2D arrays `A` and `B` (both shaped (2, 2)) to form a shape (2, 4) array using `np.concatenate`?
```python A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) hstacked = np.concatenate((A, B), axis=1) # Shape is (2, 4) ```
55
Given `arr = np.array([[1, 2], [3, 4]])`, how do you expand its dimensions to become shape (1, 2, 2) using `np.expand_dims`?
```python expanded = np.expand_dims(arr, axis=0) # expanded.shape is (1, 2, 2) ```
56
How do you remove single-dimensional entries from the shape of `arr` (for example from shape `(1, 2, 1)` to `(2,)`) using `np.squeeze`?
```python arr = np.array([[[1, 2]]]) # shape (1, 1, 2) squeezed = np.squeeze(arr) # squeezed.shape is (2,) ```
57
Given `arr = np.array([1, 2, 3])`, how do you repeat each element 3 times, resulting in `[1, 1, 1, 2, 2, 2, 3, 3, 3]`, using `np.repeat`?
```python repeated = np.repeat(arr, 3) ```
58
How do you create a 2D array by repeating the row `[1, 2]` twice vertically, resulting in `[[1, 2], [1, 2]]`, using `np.tile`?
```python row = np.array([1, 2]) tiled = np.tile(row, (2, 1)) # [[1 2], # [1 2]] ```
59
How do you generate two 2D grids for x and y coordinates between 0 and 2 (inclusive) with step 1 using `np.meshgrid`?
```python x = np.arange(0, 3) y = np.arange(0, 3) XX, YY = np.meshgrid(x, y) # XX and YY both shape (3, 3) ```
60
How do you create a diagonal 2D array from a 1D array `[10, 20, 30]` using `np.diag` so that 10, 20, 30 are on the main diagonal?
```python arr_1d = np.array([10, 20, 30]) diag_arr = np.diag(arr_1d) # [[10 0 0], # [ 0 20 0], # [ 0 0 30]] ```
61
How do you generate a single 1D array of x-values between 0 and 1 with step 0.2 using `np.arange`?
```python arr = np.arange(0, 1.01, 0.2) # [0. 0.2 0.4 0.6 0.8 1. ] ```
62
How do you randomly shuffle the rows of a 2D array `arr` in-place using `np.random.shuffle`?
```python np.random.shuffle(arr) # Shuffles along the first axis (rows) ```
63
How do you find the indices of the non-zero elements in `arr = np.array([0, 1, 2, 0, 3])` using a NumPy function?
```python indices = np.nonzero(arr) # indices is (array([1, 2, 4]),) ```
64
How do you find the positions in a 2D array `arr` where elements exceed 5, returning row and column indices?
```python positions = np.where(arr > 5) # positions is a tuple (rows, cols) of matching indices ```
65
How do you compute `arr % 2 == 0` (which checks for evenness) and then count how many even numbers are in `arr`?
```python even_mask = (arr % 2 == 0) count_even = np.sum(even_mask) ```
66
How do you reorder the elements of `arr = np.array([10, 20, 30])` using the index array `idx = [2, 0, 1]`, resulting in `[30, 10, 20]`?
```python reordered = arr[idx] ```
67
How do you take the elements at row indices `[0, 1]` and column indices `[1, 0]` respectively from a 2D array `arr` (fancy indexing)?
```python # Suppose arr.shape = (2, 2) # We want arr[0,1] and arr[1,0] extracted = arr[[0, 1], [1, 0]] ```
68
How do you stack one 2D array `A` over another 2D array `B` in a new dimension (like adding a dimension on top) using `np.stack`?
```python stacked = np.stack((A, B), axis=0) # Now stacked.shape has an extra dimension ```
69
How do you perform a split of the 2D array `arr` vertically into two sub-arrays using `np.vsplit(arr, 2)`?
```python # Suppose arr.shape = (4, 3) # vsplit will split along rows into two sub-arrays top, bottom = np.vsplit(arr, 2) ```
70
How do you perform a split of the 2D array `arr` horizontally into 3 sub-arrays using `np.hsplit(arr, 3)`?
```python # Suppose arr.shape = (2, 6) left, center, right = np.hsplit(arr, 3) ```
71
How do you find the index of the smallest element in a 1D array `arr` using `np.argmin`?
```python min_index = np.argmin(arr) ```
72
How do you get the indices that would sort the array `arr = np.array([30, 10, 20])` in ascending order using `np.argsort`?
```python sorted_indices = np.argsort(arr) # array([1, 2, 0]) for 10, 20, 30 ```
73
How do you find if there’s at least one `True` in a boolean array `bool_arr` using a single NumPy function?
```python any_true = np.any(bool_arr) ```
74
How do you check if all elements of `bool_arr` are `True` using a single NumPy function?
```python all_true = np.all(bool_arr) ```
75
How do you stack two 1D arrays `x` and `y` as columns into a 2D array using `np.column_stack`?
```python combined_2d = np.column_stack((x, y)) ```
76
How do you convert a 1D array of shape (5,) into a 2D column vector of shape (5, 1) using `np.newaxis`?
```python arr = np.array([1, 2, 3, 4, 5]) column_vec = arr[:, np.newaxis] ```
77
How do you compute the cumulative product of the elements in `arr = np.array([2, 3, 4])`, resulting in `[2, 6, 24]`?
```python cumprod_arr = np.cumprod(arr) ```
78
How do you replace elements of `arr` that are NaN (Not a Number) with 0 using `np.nan_to_num`?
```python cleaned = np.nan_to_num(arr, nan=0.0) ```
79
How do you check if any elements in `arr` are NaN using `np.isnan`?
```python has_nans = np.isnan(arr).any() ```
80
How do you generate a random seed (for reproducibility) before creating an array of random numbers in NumPy?
```python np.random.seed(42) arr = np.random.rand(3) ```
81
How do you load a NumPy array from a file named `data.npy` using `np.load`?
```python loaded_arr = np.load('data.npy') ```
82
How do you save an array `arr = np.array([1, 2, 3])` to a file named `array_data.npy` using `np.save`?
```python np.save('array_data.npy', arr) ```
83
How do you compute the element-wise natural logarithm of `arr = np.array([1, np.e, np.e**2])` using a NumPy universal function?
```python log_arr = np.log(arr) # [0., 1., 2.] ```
84
How do you compute the exponential (e^x) of every element in `arr = np.array([0, 1, 2])` using a NumPy universal function?
```python exp_arr = np.exp(arr) # [1. , 2.71828183, 7.3890561 ] ```
85
How do you compute `arr1 + arr2` only where `arr2 != 0` and 0 otherwise, using `np.where`?
```python result = np.where(arr2 != 0, arr1 + arr2, 0) ```
86
How do you identify elements in `arr` that are finite (i.e., not infinity) using `np.isfinite`?
```python finite_mask = np.isfinite(arr) ```
87
How do you compute the boolean array indicating which elements of `arr` are greater than the mean of `arr`?
```python mean_val = arr.mean() mask = arr > mean_val ```
88
How do you sort a 2D array `arr` by its second column in ascending order using `argsort` and fancy indexing?
```python sort_indices = np.argsort(arr[:, 1]) arr_sorted = arr[sort_indices] ```
89
How do you select the top 3 largest elements from `arr = np.array([10, 20, 5, 40, 15])` without fully sorting it? (Hint: `np.argpartition`)
```python top_k = 3 indices = np.argpartition(arr, -top_k)[-top_k:] largest_three = arr[indices] ```
90
How do you remove duplicate rows from a 2D array `arr` using `np.unique` with `axis=0`?
```python unique_rows = np.unique(arr, axis=0) ```
91
How do you find the row-wise maximum value in a 2D array `arr` using `np.max` with an axis?
```python row_wise_max = np.max(arr, axis=1) ```
92
How do you compute the average of `arr` ignoring any NaN values, using a NumPy function?
```python mean_ignoring_nan = np.nanmean(arr) ```
93
How do you extract the real part of a complex array `carr = np.array([1+2j, 3+4j])` using NumPy?
```python real_part = carr.real # [1., 3.] ```
94
How do you extract the imaginary part of a complex array `carr = np.array([1+2j, 3+4j])` using NumPy?
```python imag_part = carr.imag # [2., 4.] ```
95
How do you convert the integer array `arr = np.array([1, 2, 3])` into a floating-point array *in place* (if possible)?
```python arr = arr.astype(float, copy=False) ```
96
How do you swap the first and second axes of a 3D array `arr` from shape (2, 3, 4) to (3, 2, 4) using `np.swapaxes`?
```python swapped = np.swapaxes(arr, 0, 1) ```
97
How do you split a 1D array `arr` at positions `[2, 5]` using `np.split`, resulting in three sub-arrays?
```python sub1, sub2, sub3 = np.split(arr, [2, 5]) ```
98
How do you swap axes of an array `arr` from (3, 2, 4) to (2, 3, 4) using `np.swapaxes`?
```python swapped = np.swapaxes(arr, 0, 1) ```
99
How do you find elements of `arr = np.array([1, 2, 3, 4])` that belong to a set of allowed values `[2, 4, 5]` using `np.in1d`?
```python mask = np.in1d(arr, [2, 4, 5]) # mask is [False, True, False, True] ```
100
How do you compute the pairwise minimum between two same-shaped arrays `a` and `b` using a NumPy universal function?
```python min_pairwise = np.minimum(a, b) ```
101
How do you compute the pairwise maximum between two same-shaped arrays `a` and `b` using a NumPy universal function?
```python max_pairwise = np.maximum(a, b) ```
102
How do you generate an array of 6 values spaced evenly on a log scale between (10^0) and (10^3) using NumPy?
```python import numpy as np arr = np.logspace(0, 3, 6) # e.g., [ 1. 3.98107171 15.84893192 63.09573445 251.18864315 # 1000. ]```
103
How do you find the discrete difference between consecutive elements of `arr = np.array([10, 13, 15, 20])`, resulting in `[3, 2, 5]`?
```python diff_arr = np.diff(arr) # [3 2 5]```
104
How do you roll (circularly shift) the elements of `arr = np.array([1, 2, 3, 4])` by 2 positions to the right, resulting in `[3, 4, 1, 2]`?
```python rolled_arr = np.roll(arr, 2)```
105
How do you broadcast a 1D array `[1, 2, 3]` to the shape (2, 3) without adding new data (just a view), using `np.broadcast_to`?
```python arr = np.array([1, 2, 3]) broadcasted = np.broadcast_to(arr, (2, 3))```
106
How do you create a 1D array by interpreting a buffer of bytes in little-endian order, for example `b"\x01\x00\x02\x00"` as dtype `
```python buffer = b"\x01\x00\x02\x00" arr = np.frombuffer(buffer, dtype='
107
How do you create a masked array from `data = np.array([1, -1, 3, -1])` by masking all `-1` values using `np.ma.masked_equal`?
```python import numpy as np masked_arr = np.ma.masked_equal(data, -1) # masked values appear as --```
108
How do you fill all masked values in a masked array `m_arr` with a given fill value, say `0`, using `m_arr.filled(0)`?
```python filled_arr = m_arr.filled(0)```
109
How do you check if two float arrays `a` and `b` are element-wise approximately equal (within a tolerance) using `np.isclose`?
```python import numpy as np close_mask = np.isclose(a, b, atol=1e-8) # Returns a boolean array```
110
How do you check if two arrays `a` and `b` have the same shape and elements (within a numerical tolerance) using `np.allclose`?
```python are_close = np.allclose(a, b, atol=1e-8)```
111
How do you check if two arrays `a` and `b` have exactly the same shape and elements (no tolerance) using `np.array_equal`?
```python equal = np.array_equal(a, b)```
112
How do you force an array `arr` to have data type `float64` using the `dtype` parameter in `np.array`?
```python float_arr = np.array(arr, dtype=np.float64)```
113
How do you compute the gradient (discrete derivative) of a 1D array `arr = np.array([1, 2, 4, 7])` using `np.gradient`?
```python grad = np.gradient(arr) # For [1, 2, 4, 7], np.gradient yields [1. , 1.5, 2.5, 3. ]```
114
How do you parse a CSV file named `data.csv` into a NumPy array using `np.loadtxt`, assuming it has floating-point data and no headers?
```python arr = np.loadtxt('data.csv', delimiter=',')```
115
How do you save an array `arr` to a text file named `output.txt` with each row on its own line, using `np.savetxt`?
```python np.savetxt('output.txt', arr, fmt='%.2f')```
116
How do you use `np.genfromtxt` to handle missing values (treat them as `-999.0` for instance) in a file named `data.txt`?
```python arr = np.genfromtxt('data.txt', delimiter=',', filling_values=-999.0)```
117
How do you find the histogram of values in `arr = np.array([1, 2, 2, 3])` using `np.histogram` with bins `[1, 2, 3, 4]`?
```python counts, bin_edges = np.histogram(arr, bins=[1,2,3,4]) # counts: array([1, 2, 1]), bin_edges: [1, 2, 3, 4]```
118
How do you count the number of occurrences of each integer value in `arr = np.array([0, 1, 1, 2, 2, 2])` using `np.bincount`?
```python counts = np.bincount(arr) # [1, 2, 3]```
119
How do you extract elements from `arr = np.array([10, 20, 30])` at indices `[0, 2]` using `np.take`?
```python extracted = np.take(arr, [0, 2]) # [10, 30]```
120
How do you place values `[100, 200]` into the array `arr = np.array([10, 20, 30, 40])` at indices `[1, 3]` using `np.put`?
```python np.put(arr, [1, 3], [100, 200]) # arr becomes [ 10 100 30 200]```
121
How do you replace elements in `arr = np.array([10, 20, 30, 40])` with 99 wherever a mask `mask = [False, True, False, True]` is True, using `np.putmask`?
```python np.putmask(arr, mask, 99) # arr becomes [10 99 30 99]```
122
How do you generate an array of 5 random floats from a standard normal distribution (mean=0, std=1) using `np.random.randn`?
```python rand_nums = np.random.randn(5)```
123
How do you generate a 1D array of length 4 with random floats sampled from a normal distribution with mean=10 and std=2, using `np.random.normal`?
```python arr = np.random.normal(loc=10, scale=2, size=4)```
124
How do you generate a random choice of 3 elements from the array `[10, 20, 30, 40]` with replacement, using `np.random.choice`?
```python arr = np.array([10, 20, 30, 40]) choice_result = np.random.choice(arr, size=3, replace=True)```
125
How do you ensure reproducibility by setting a random seed of 42 before generating random numbers with `np.random`?
```python np.random.seed(42) # subsequent random calls will be reproducible```
126
How do you create a structured array that has fields `name` (string) and `age` (integer) using `np.array` with a specified `dtype`?
```python data = np.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'U10'), ('age', 'i4')])```
127
How do you access the `name` field of the structured array `data` from the previous flashcard?
```python names = data['name']```
128
How do you find the union of two 1D arrays `a = [1, 2, 3]` and `b = [3, 4, 5]` using `np.union1d`?
```python union = np.union1d(a, b) # [1, 2, 3, 4, 5]```
129
How do you find the set difference `a - b` for `a = [1, 2, 3]` and `b = [2, 4]` using `np.setdiff1d` (order is the first array’s order)?
```python difference = np.setdiff1d(a, b) # [1, 3]```
130
How do you find the intersection of `a = [1, 2, 3]` and `b = [2, 3, 4]` using `np.intersect1d`?
```python intersection = np.intersect1d(a, b) # [2, 3]```
131
How do you compare two arrays element-wise to see which elements of `a` are smaller than `b`?
```python result = a < b # Boolean array```
132
How do you compute the 50th percentile (median) of `arr` using `np.percentile(arr, 50)`?
```python median_val = np.percentile(arr, 50)```
133
How do you compute the quantile at probability 0.75 (the 75th percentile) of `arr` using `np.quantile`?
```python q75 = np.quantile(arr, 0.75)```
134
How do you compute the covariance matrix of two 1D arrays `x` and `y` using `np.cov(x, y)`?
```python cov_matrix = np.cov(x, y) # 2x2 matrix```
135
How do you compute the correlation coefficient matrix of two 1D arrays `x` and `y` using `np.corrcoef(x, y)`?
```python corr_matrix = np.corrcoef(x, y) # 2x2 matrix```
136
How do you fit a polynomial of degree 2 to points `(x, y)` using `np.polyfit(x, y, 2)`, obtaining the polynomial coefficients?
```python coeffs = np.polyfit(x, y, 2) # e.g., [a, b, c] for ax^2 + bx + c```
137
How do you evaluate a polynomial with given coefficients `p = [1, 2, 3]` (meaning (x^2 + 2x + 3)) at points `x` using `np.polyval`?
```python y_vals = np.polyval(p, x)```
138
How do you define a polynomial object `p(x) = x^2 + 2x + 3` using `np.poly1d` and evaluate it at `x=5`?
```python p = np.poly1d([1, 2, 3]) val_at_5 = p(5)```
139
How do you compute the inverse of a 2x2 matrix `M` using `np.linalg.inv`?
```python import numpy as np inv_M = np.linalg.inv(M)```
140
How do you compute the determinant of a 2D square matrix `M` using `np.linalg.det`?
```python det_val = np.linalg.det(M)```
141
How do you compute eigenvalues and eigenvectors of a square matrix `M` using `np.linalg.eig`?
```python eigenvals, eigenvecs = np.linalg.eig(M)```
142
How do you solve the linear system `A x = b` using `np.linalg.solve(A, b)`?
```python x = np.linalg.solve(A, b)```
143
How do you compute the Euclidean norm ((\|x\|)) of a vector `x` using `np.linalg.norm`?
```python norm_val = np.linalg.norm(x)```
144
How do you create an array of shape (3, 3) using a function that depends on the indices, for example `f(i, j) = i + j`, with `np.fromfunction`?
```python f = lambda i, j: i + j arr = np.fromfunction(f, (3, 3), dtype=int)```
145
How do you create a 1D array from an iterable, say `range(5)`, using `np.fromiter` with a data type of `float`?
```python arr = np.fromiter(range(5), dtype=float) # [0. 1. 2. 3. 4.]```
146
How do you broadcast two arrays of different but compatible shapes using `np.broadcast_arrays` and see their broadcasted shapes?
```python A = np.array([1, 2, 3]) B = np.array([[10], [20]]) bA, bB = np.broadcast_arrays(A, B) # Now bA.shape = (2, 3), bB.shape = (2, 3)```
147
How do you split a 2D array `M` into multiple arrays along a custom axis using `np.array_split`?
```python # Example code not provided in the original text```
148
How do you broadcast two arrays of different but compatible shapes using np.broadcast_arrays?
```python A = np.array([1, 2, 3]) B = np.array([[10], [20]]) bA, bB = np.broadcast_arrays(A, B) # Now bA.shape = (2, 3), bB.shape = (2, 3) ```
149
How do you split a 2D array M into multiple arrays along a custom axis using np.array_split?
```python parts = np.array_split(M, 3, axis=1) ```
150
How do you find all pairwise sums between A = [1, 2] and B = [10, 20, 30] using broadcasting?
```python A_2D = A[:, np.newaxis] # shape (2, 1) result = A_2D + B # shape (2, 3) ```
151
How do you create a 'deep' copy of a NumPy array arr?
```python copied_arr = arr.copy() ```
152
How do you convert an integer array arr = np.array([1, 2, 3]) into a Python list?
```python py_list = arr.tolist() ```
153
How do you generate a random permutation of the integers from 0 to 4 using np.random.permutation(5)?
```python perm = np.random.permutation(5) # e.g., [3 0 4 1 2] ```
154
How do you create a 1D array `arr` of 5 values, all initialized to \(\pi\) (using `np.pi`) with float data type?
```python import numpy as np arr = np.full(5, np.pi, dtype=float) ```
155
How do you round all the values in `arr = np.array([0.1, 1.9, 2.5, 3.49])` to the nearest integer using `np.round`?
```python rounded = np.round(arr) # [0. 2. 2. 3.] ```
156
How do you floor (round down) all the values in `arr = np.array([1.1, 2.9, 3.5])` using `np.floor`?
```python floored = np.floor(arr) # [1. 2. 3.] ```
157
How do you ceiling (round up) all the values in `arr = np.array([1.1, 2.9, 3.5])` using `np.ceil`?
```python ceiled = np.ceil(arr) # [2. 3. 4.] ```
158
How do you truncate (remove the decimal part) of `arr = np.array([1.9, -2.5, 3.99])` using `np.trunc`?
```python truncated = np.trunc(arr) # [ 1. -2. 3.] ```
159
How do you compute the sign of each element in `arr = np.array([-3, 0, 2])` using `np.sign`?
```python signs = np.sign(arr) # [-1, 0, 1] ```
160
How do you flatten a 2D array `arr` into a 1D array using `.flatten()` (which returns a copy)?
```python arr_1d_copy = arr.flatten() ```
161
How do you flatten a 2D array `arr` into a 1D view (if possible) using `.ravel()`?
```python arr_1d_view = arr.ravel() ```
162
How do you flip (reverse) the order of elements in a 1D array `arr = np.array([1, 2, 3, 4])` using `np.flip`?
```python flipped = np.flip(arr) # [4 3 2 1] ```
163
How do you flip the rows up/down in a 2D array `mat` using `np.flipud`?
```python flipped_ud = np.flipud(mat) # The top row becomes bottom row, etc. ```
164
How do you flip the columns left/right in a 2D array `mat` using `np.fliplr`?
```python flipped_lr = np.fliplr(mat) # The leftmost column becomes rightmost, etc. ```
165
How do you rotate (shift) the axes of a 3D array `arr` so that axis 0 moves to axis 2, using `np.rollaxis`?
```python rolled = np.rollaxis(arr, 0, 3) # Moves axis 0 to position 2 ```
166
How do you move axis 0 to axis 1 in a 3D array `arr` using `np.moveaxis(arr, 0, 1)`?
```python moved = np.moveaxis(arr, 0, 1) ```
167
How do you pad a 1D array `arr = np.array([1, 2, 3])` with two zeros on the left and one zero on the right using `np.pad`?
```python padded = np.pad(arr, (2, 1), mode='constant', constant_values=0) # [0 0 1 2 3 0] ```
168
How do you compute both the floor and remainder of division, for instance `arr / 2`, using `np.divmod(arr, 2)`?
```python quotient, remainder = np.divmod(arr, 2) ```
169
How do you generate indices for a 3D grid of shape (2, 3, 4) using `np.indices`?
```python grid = np.indices((2, 3, 4)) # grid is a tuple of arrays representing x, y, z indices ```
170
How do you enumerate over every index-value pair in a 2D array `arr` using `np.ndenumerate(arr)` in a loop?
```python for idx, val in np.ndenumerate(arr): print(idx, val) ```
171
How do you return the flattened indices of all non-zero elements from `arr = np.array([[0, 1], [2, 0]])` using `np.flatnonzero`?
```python indices = np.flatnonzero(arr) # [1, 2] ```
172
How do you convert a multi-dimensional index `(row, col)` into a single flat index for a given shape using `np.ravel_multi_index`?
```python flat_index = np.ravel_multi_index((row, col), shape=(n_rows, n_cols)) ```
173
How do you convert a single flat index `idx` back to a multi-dimensional index `(row, col)` using `np.unravel_index`?
```python row, col = np.unravel_index(idx, shape=(n_rows, n_cols)) ```
174
How do you determine if two arrays `x` and `y` might share the same memory (view) using `np.may_share_memory`?
```python shares_mem = np.may_share_memory(x, y) ```
175
How do you get the total number of elements in a NumPy array `arr` using the `.size` attribute?
```python num_elements = arr.size ```
176
How do you find the size (in bytes) of each element in `arr` using the `.itemsize` attribute?
```python bytes_per_element = arr.itemsize ```
177
How do you find the total number of bytes consumed by a NumPy array `arr` using the `.nbytes` attribute?
```python total_bytes = arr.nbytes ```
178
How do you find the `dtype` (data type) of a NumPy array `arr` using the `.dtype` attribute?
```python array_dtype = arr.dtype ```
179
How do you add a condition to select elements from `arr` only if they are between 3 and 7 (exclusive), using boolean indexing with `&`?
```python selected = arr[(arr > 3) & (arr < 7)] ```
180
How do you randomly choose 4 elements from `arr` with probabilities given by `p`, using `np.random.choice(arr, size=4, p=p)`?
```python chosen = np.random.choice(arr, size=4, replace=True, p=p) ```
181
How do you compute the inner product of two 1D arrays `a` and `b` using `np.dot(a, b)`?
```python dot_val = np.dot(a, b) ```
182
How do you compute the cross product of two 3D vectors `a` and `b` using `np.cross(a, b)`?
```python cross_val = np.cross(a, b) ```
183
How do you convolve two 1D arrays `x` and `y` using `np.convolve(x, y, mode='full')`?
```python conv_result = np.convolve(x, y, mode='full') ```
184
How do you compute the upper-triangular part of a 2D matrix `M` (including the main diagonal) using `np.triu(M)`?
```python upper_tri = np.triu(M) ```
185
How do you compute the lower-triangular part of a 2D matrix `M` (including the main diagonal) using `np.tril(M)`?
```python lower_tri = np.tril(M) ```
186
How do you calculate the median of a 1D array `arr` using `np.median`?
```python med_val = np.median(arr) ```
187
How do you check which elements of `arr = np.array([1, 2, np.inf, 3])` are infinite using `np.isinf`?
```python inf_mask = np.isinf(arr) # [False, False, True, False] ```
188
How do you compute the power of two arrays `a` and `b` (i.e., `a**b`) using the universal function `np.power(a, b)`?
```python power_result = np.power(a, b) ```
189
How do you select from multiple conditions in `arr` using `np.select`? For example, if `arr<0` set to -1, if `arr>0` set to +1, else 0.
```python conditions = [arr < 0, arr > 0] choices = [-1, 1] selected = np.select(conditions, choices, default=0) ```
190
How do you apply a function `f(x)` along axis 1 of a 2D array `arr` using `np.apply_along_axis(f, 1, arr)`?
```python def f(row): return np.sum(row) # example function result = np.apply_along_axis(f, 1, arr) ```
191
How do you check if any element of a 2D boolean array `bool_2d` is True along axis 0, producing a 1D result, using `np.any`?
```python any_true_axis0 = np.any(bool_2d, axis=0) ```
192
How do you check if all elements of a 2D boolean array `bool_2d` are True along axis 1, producing a 1D result, using `np.all`?
```python all_true_axis1 = np.all(bool_2d, axis=1) ```
193
How do you compute the logical AND of two boolean arrays `mask1` and `mask2` element-wise using `np.logical_and`?
```python combined_mask = np.logical_and(mask1, mask2) ```
194
How do you compute the logical OR of two boolean arrays `mask1` and `mask2` element-wise using `np.logical_or`?
```python combined_mask = np.logical_or(mask1, mask2) ```
195
How do you transpose a 2D array `arr` (swap rows and columns) using `arr.T`?
```python transposed = arr.T ```
196
How do you access the linear iterator over all elements in `arr` using `arr.flat` in a loop?
```python for value in arr.flat: print(value) ```
197
How do you change the printing options so NumPy arrays use a precision of 2 decimal places using `np.set_printoptions`?
```python np.set_printoptions(precision=2) ```
198
How do you compute the cumulative product of elements along axis=1 of a 2D array `arr` using `np.cumprod(arr, axis=1)`?
```python row_cumprod = np.cumprod(arr, axis=1) ```
199
How do you check if `arr` is a single-dimensional array (`arr.ndim == 1`) in a Pythonic way?
```python if arr.ndim == 1: print("arr is 1D") ```
200
How do you convert each element of an array of strings `str_arr` to uppercase using vectorized `np.char.upper`?
```python upper_arr = np.char.upper(str_arr) ```
201
How do you convert each element of an array of strings `str_arr` to an integer, assuming they are numeric, using `arr.astype(int)`?
```python int_arr = str_arr.astype(int) ```
202
How do you compute the matrix product between two 2D arrays `A` and `B` (both shape `(2,2)`) using the `@` operator?
```python result = A @ B ```
203
How do you create a 2D array block by combining smaller arrays using `np.block`, for example: \[ \begin{pmatrix} A & B \\ C & D \end{pmatrix} \]?
```python A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) C = np.array([[9, 10], [11, 12]]) D = np.array([[13, 14], [15, 16]]) block_mat = np.block([ [A, B], [C, D] ]) ```