import numpy as np
# 1. How does np.empty() differ from np.zeros()?
a = np.empty((2, 3)) # Uninitialized values
b = np.zeros((2, 3)) # All zeros
print(a, "\n", b)
# 2. Typecasting float array to int
c = np.array([1.5, 2.8, 3.2], dtype=np.float32).astype(int)
print(c) # Output: [1, 2, 3]
# 3. np.array() vs np.asarray()
d = np.array([1, 2, 3])
e = np.asarray(d) # No new copy created
print(d is e) # Output: True
# 4. Difference between np.linspace() and np.arange()
f = np.linspace(0, 10, 5) # Generates evenly spaced numbers
g = np.arange(0, 10, 2.5) # Step-based range
print(f, g)
# 5. Integer overflow in np.int8
h = np.ones((2, 2), dtype=np.int8) * 300
print(h) # Unexpected values due to overflow
# 6. np.full() vs np.ones()
i = np.full((3, 3), 5)
j = np.ones((3, 3)) * 5
print(i, j)
# 7. np.eye() vs np.identity()
k = np.eye(4)
l = np.identity(4)
print(np.array_equal(k, l)) # Output: True
# 8. Reverse an array
m = np.arange(10)[::-1]
print(m) # Output: [9 8 7 6 5 4 3 2 1 0]
# 9. np.zeros_like() vs np.empty_like()
x = np.array([1, 2, 3])
n = np.zeros_like(x)
o = np.empty_like(x) # Uninitialized values
print(n, o)
# 10. String conversion in NumPy
p = np.array([1, 2, 3, "4"])
print(p.dtype) # Output: <U21> (string type)
# 11. np.tile() usage
q = np.tile([1, 2, 3], (2, 3))
print(q)
# 12. Memory efficiency of np.asarray()
r = np.array([1, 2, 3])
s = np.asarray(r)
print(r is s) # Output: True
# 13. Reshaping and transposing
t = np.arange(10).reshape(2, 5)
u = np.arange(10).reshape(5, 2).T
print(t.shape, u.shape)
# 14. np.diag() behavior
v = np.diag([1, 2, 3])
print(v)
# 15. Creating a checkerboard pattern
checkerboard = np.zeros((5, 5), dtype=int)
checkerboard[::2, 1::2] = 1
checkerboard[1::2, ::2] = 1
print(checkerboard)
# 16. Division by zero warning
w = np.full((2, 2), np.inf) / np.full((2, 2), 0)
print(w) # Output: inf or nan
# 17. Creating a random 3D array
rand_array = np.random.rand(3, 3, 3)
print(rand_array)
# 18. Floating point precision in arange
precision = np.arange(0, 1, 0.1).dtype
print(precision) # Output: float64
# 19. Difference between tuple and list in shape input
y = np.zeros((2, 2))
z = np.zeros([2, 2])
print(y.shape == z.shape) # Output: True
# 20. dtype preservation in ones()
a1 = np.ones((3, 4), dtype=int).dtype
a2 = np.ones((3, 4)).astype(int).dtype
print(a1, a2) # Output: int64 int64
# 1. Type conversion in NumPy arrays
b1 = np.array([1.5, 2.8, 3.2], dtype=int)
print(b1) # Output: [1 2 3]
# 2. Boolean array dtype
b2 = np.array([True, False, 1, 0])
print(b2.dtype) # Output: int32
# 3. Default dtype for integer array
b3 = np.array([1, 2, 3])
print(b3.dtype) # Output: int64 or int32
# 4. Type promotion rules
b4 = np.array([1, 2.5, True])
print(b4.dtype) # Output: float64
# 5. String to integer conversion error
# np.array(['1', '2', '3'], dtype=int) # Raises ValueError
# 6. Smallest dtype for value up to 1000
b5 = np.array([1000], dtype=np.uint16)
print(b5.dtype) # Output: uint16
# 7. Precision difference
b6 = np.float16(0.1)
b7 = np.float64(0.1)
print(b6, b7)
# 8. Storing large floats in int32
b8 = np.array([1e20], dtype=np.int32)
print(b8) # Undefined behavior (overflow)
# 9. Boolean conversion
b9 = np.array([1, 0, -5], dtype=np.bool_)
print(b9) # Output: [ True False True]
# 10. Converting int array to float
b10 = np.array([1, 2, 3]).astype(float)
print(b10) # Output: [1. 2. 3.]
# 11. Max value of int16
b11 = np.iinfo(np.int16).max
print(b11) # Output: 32767
# 12. Internal storage of datetime64
b12 = np.datetime64('2024-01-01').astype(int)
print(b12) # Output: Integer timestamp
# 13. Complex dtype differences
b13 = np.array([1+2j], dtype=np.complex64)
print(b13.dtype) # Output: complex64
# 14. Floating-point precision error
b14 = np.float32(0.1) + np.float32(0.2) == np.float32(0.3)
print(b14) # Output: False
# 15. Overflow in uint8
b15 = np.array([1, 2, 3], dtype=np.uint8) - 300
print(b15) # Unexpected values due to overflow
# 16. Boolean and integer addition
b16 = np.array([True, False, False]) + np.array([1, 2, 3])
print(b16) # Output: [2 2 3]
# 17. Using object dtype
b17 = np.asarray([1, 2, 3], dtype="O")
print(b17.dtype) # Output: object
# 18. Casting datetime to int
b18 = np.array(['2024-01-01'], dtype='datetime64[D]').astype(int)
print(b18) # Output: Integer timestamp
# 19. Complex dtype equivalent
b19 = np.array([1+2j]).dtype
print(b19) # Output: complex128
# 20. dtype=int vs dtype=np.int64
b20 = np.array([1, 2, 3], dtype=int).dtype
print(b20) # Output: int64
# 1. Element-wise addition of different shapes
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
c=a+b
print(c) # Output: [[2 3 4] [3 4 5] [4 5 6]]
# 2. What happens when adding a scalar to an array?
d = np.array([1, 2, 3]) + 5
print(d) # Output: [6 7 8]
# 3. How does NumPy handle division by zero?
e = np.array([1, 0, -1]) / np.array([0, 0, 0])
print(e) # Output: [ inf nan -inf]
# 4. Difference between * and np.dot() for 2D arrays
f = np.array([[1, 2], [3, 4]])
g = np.array([[2, 0], [1, 2]])
print(f * g) # Element-wise multiplication
print(np.dot(f, g)) # Matrix multiplication
# 5. How does broadcasting work in subtraction?
h = np.array([10, 20, 30])
i = np.array([[1], [2], [3]])
print(h - i) # Output: [[9 19 29] [8 18 28] [7 17 27]]
# 6. Power operator behavior
j = np.array([2, 3, 4]) ** 2
print(j) # Output: [ 4 9 16]
# 7. NumPy's modulo behavior with negatives
k = np.array([-10, -5, 5, 10]) % 3
print(k) # Output: [2 1 2 1]
# 8. Exponentiation with np.exp()
l = np.exp(np.array([0, 1, 2]))
print(l) # Output: [ 1. 2.71828183 7.3890561 ]
# 9. Logarithm of zero
m = np.log(np.array([0, 1, 10]))
print(m) # Output: [-inf 0. 2.30258509]
# 10. Comparing two NumPy arrays
n = np.array([1, 2, 3])
o = np.array([1, 2, 4])
print(n == o) # Output: [ True True False]
# 11. Adding a column vector to a row vector
p = np.array([[1], [2], [3]])
q = np.array([1, 2, 3])
print(p + q) # Output: [[2 3 4] [3 4 5] [4 5 6]]
# 12. Combining arithmetic with boolean indexing
r = np.array([1, 2, 3, 4])
r[r % 2 == 0] += 10
print(r) # Output: [ 1 12 3 14]
# 13. What does np.ceil() do?
s = np.array([1.2, 2.5, 3.7])
print(np.ceil(s)) # Output: [2. 3. 4.]
# 14. Handling NaN values in arithmetic operations
t = np.array([1, np.nan, 2])
print(t + 2) # Output: [ 3. nan 4.]
# 15. What happens when multiplying by a boolean array?
u = np.array([1, 2, 3]) * np.array([True, False, True])
print(u) # Output: [1 0 3]
# 16. How does np.clip() work?
v = np.array([-5, 0, 5, 10])
print(np.clip(v, 0, 5)) # Output: [0 0 5 5]
# 17. Effect of np.round() on negative numbers
w = np.round(np.array([-1.5, -2.5, 1.5, 2.5]))
print(w) # Output: [-2. -2. 2. 2.]
# 18. Difference between np.floor_divide() and // operator
x = np.array([5, -5]) // 2
y = np.floor_divide(np.array([5, -5]), 2)
print(x, y) # Output: [ 2 -3] [ 2 -3]
# 19. Combining np.maximum() and np.minimum()
z = np.maximum(np.array([1, 5, 10]), np.array([2, 4, 8]))
print(z) # Output: [ 2 5 10]
# 20. How does np.abs() handle complex numbers?
a1 = np.abs(np.array([1 + 2j, -3 + 4j]))
print(a1) # Output: [2.23606798 5.]
import numpy as np
# 1. Extract every second element from an array
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(a[::2]) # Output: [0 2 4 6 8]
# 2. Reverse an array
b = np.array([10, 20, 30, 40])
print(b[::-1]) # Output: [40 30 20 10]
# 3. Slicing a 2D array
c = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(c[:2, 1:]) # Output: [[2 3] [5 6]]
# 4. Modify a slice and observe changes in original array
d = np.array([1, 2, 3, 4, 5])
slice_d = d[1:4]
slice_d[:] = 99
print(d) # Output: [ 1 99 99 99 5]
# 5. Extract last column of a 2D array
e = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(e[:, -1]) # Output: [3 6 9]
# 6. Extract a diagonal from a 2D array
f = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
print(f.diagonal()) # Output: [10 50 90]
# 7. Selecting a sub-matrix
g = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(g[1:, 1:3]) # Output: [[ 6 7] [10 11]]
# 8. Setting an entire row to a single value
h = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
h[1, :] = 99
print(h) # Output: [[ 1 2 3] [99 99 99] [ 7 8 9]]
# 9. Using step values in slicing
i = np.array([10, 20, 30, 40, 50, 60])
print(i[1::2]) # Output: [20 40 60]
# 10. Negative indices for slicing
j = np.array([1, 2, 3, 4, 5])
print(j[-3:]) # Output: [3 4 5]
# 11. Selecting non-contiguous elements using indexing
k = np.array([10, 20, 30, 40, 50])
indices = [0, 2, 4]
print(k[indices]) # Output: [10 30 50]
# 12. Reshape and access elements
l = np.arange(1, 10).reshape(3, 3)
print(l[1, 2]) # Output: 6
# 13. Swapping rows in a matrix
m = np.array([[1, 2, 3], [4, 5, 6]])
m[[0, 1]] = m[[1, 0]]
print(m) # Output: [[4 5 6] [1 2 3]]
# 14. Extracting an entire column
n = np.array([[10, 20, 30], [40, 50, 60]])
print(n[:, 1]) # Output: [20 50]
# 15. Accessing an element using multiple indices
o = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(o[(0, 1)]) # Output: 2
# 16. Checking if a slice is a view or a copy
p = np.array([1, 2, 3, 4])
slice_p = p[1:3]
slice_p[0] = 99
print(p) # Output: [ 1 99 3 4] (shows it's a view)
# 17. Extracting every other row in a 2D array
q = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(q[::2]) # Output: [[ 1 2 3] [ 7 8 9]]
# 18. Using np.take() for advanced indexing
r = np.array([100, 200, 300, 400])
print(np.take(r, [0, 2, 3])) # Output: [100 300 400]
# 19. Multi-dimensional slicing
s = np.arange(16).reshape(4, 4)
print(s[1:3, 2:]) # Output: [[ 6 7] [10 11]]
# 20. Swapping columns in a 2D array
t = np.array([[1, 2, 3], [4, 5, 6]])
t[:, [0, 2]] = t[:, [2, 0]]
print(t) # Output: [[3 2 1] [6 5 4]]
import numpy as np
# 1. Extract all even numbers from an array
a = np.array([1, 2, 3, 4, 5, 6])
print(a[a % 2 == 0]) # Output: [2 4 6]
# 2. Extract all elements greater than a given value
b = np.array([10, 20, 30, 40, 50])
print(b[b > 25]) # Output: [30 40 50]
# 3. Replace negative values with zero
c = np.array([-1, 2, -3, 4])
c[c < 0] = 0
print(c) # Output: [0 2 0 4]
# 4. Count the number of values greater than a threshold
d = np.array([3, 7, 1, 9, 12])
print(np.sum(d > 5)) # Output: 3
# 5. Select elements based on a condition from another array
e = np.array([10, 20, 30, 40, 50])
mask = np.array([True, False, True, False, True])
print(e[mask]) # Output: [10 30 50]
# 6. Find indices of all nonzero elements
f = np.array([0, 1, 0, 2, 3, 0])
print(np.nonzero(f)) # Output: (array([1, 3, 4]),)
# 7. Extract values in a given range
g = np.array([5, 15, 25, 35, 45])
print(g[(g > 10) & (g < 40)]) # Output: [15 25 35]
# 8. Invert a Boolean mask
h = np.array([True, False, True, False])
print(~h) # Output: [False True False True]
# 9. Set values above a threshold to a maximum limit
i = np.array([10, 25, 40, 55])
i[i > 30] = 30
print(i) # Output: [10 25 30 30]
# 10. Extract odd numbers from an array
j = np.array([11, 22, 33, 44, 55])
print(j[j % 2 == 1]) # Output: [11 33 55]
# 11. Use Boolean indexing to assign a new value
k = np.array([3, 7, 2, 9])
k[k > 5] = 99
print(k) # Output: [ 3 99 2 99]
# 12. Get elements not equal to a specific value
l = np.array([1, 2, 3, 2, 1])
print(l[l != 2]) # Output: [1 3 1]
# 13. Find the maximum value of only positive numbers
m = np.array([-5, 0, 10, 20, -3])
print(np.max(m[m > 0])) # Output: 20
# 14. Find indices of elements matching a condition
n = np.array([5, 15, 25, 35])
print(np.where(n > 20)) # Output: (array([2, 3]),)
# 15. Create a mask based on multiple conditions
o = np.array([10, 20, 30, 40, 50])
mask = (o > 15) & (o < 45)
print(o[mask]) # Output: [20 30 40]
# 16. Extract elements using np.flatnonzero()
p = np.array([0, 2, 4, 0, 8])
print(np.flatnonzero(p)) # Output: [1 2 4]
# 17. Select every second element greater than a threshold
q = np.array([1, 20, 3, 40, 5, 60])
print(q[q > 10][::2]) # Output: [20 5]
# 18. Extract elements that are not NaN
r = np.array([1, np.nan, 3, np.nan, 5])
print(r[~np.isnan(r)]) # Output: [1. 3. 5.]
# 19. Check if any element satisfies a condition
s = np.array([10, 20, 30])
print(np.any(s > 25)) # Output: True
# 20. Check if all elements satisfy a condition
t = np.array([10, 20, 30])
print(np.all(t > 5)) # Output: True
import numpy as np
# 1. Select multiple elements using an index list
a = np.array([10, 20, 30, 40, 50])
indices = [0, 2, 4]
print(a[indices]) # Output: [10 30 50]
# 2. Select specific rows from a 2D array
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row_indices = [0, 2]
print(b[row_indices])
# Output: [[1 2 3]
# [7 8 9]]
# 3. Select specific columns from a 2D array
col_indices = [1, 2]
print(b[:, col_indices])
# Output: [[2 3]
# [5 6]
# [8 9]]
# 4. Extract diagonal elements using fancy indexing
c = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
diagonal_indices = [0, 1, 2]
print(c[diagonal_indices, diagonal_indices]) # Output: [1 5 9]
# 5. Select elements in reverse order using fancy indexing
d = np.array([100, 200, 300, 400])
reverse_indices = [3, 2, 1, 0]
print(d[reverse_indices]) # Output: [400 300 200 100]
# 6. Select non-contiguous rows and columns
e = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
row_indices = [0, 2]
col_indices = [1, 2]
print(e[np.ix_(row_indices, col_indices)])
# Output: [[20 30]
# [80 90]]
# 7. Modify elements using fancy indexing
f = np.array([1, 2, 3, 4, 5])
indices = [1, 3]
f[indices] = 99
print(f) # Output: [ 1 99 3 99 5]
# 8. Duplicate elements using fancy indexing
g = np.array([1, 2, 3, 4])
print(g[[0, 0, 2]]) # Output: [1 1 3]
# 9. Shuffle an array using fancy indexing
h = np.array([10, 20, 30, 40, 50])
shuffled_indices = np.random.permutation(len(h))
print(h[shuffled_indices])
# 10. Extract elements greater than a threshold using fancy indexing
i = np.array([10, 25, 30, 5, 50])
print(i[np.where(i > 20)]) # Output: [25 30 50]
# 11. Select every second element using fancy indexing
j = np.array([5, 10, 15, 20, 25, 30])
print(j[np.arange(0, len(j), 2)]) # Output: [ 5 15 25]
# 12. Modify multiple elements at once using fancy indexing
k = np.array([1, 2, 3, 4, 5])
k[[0, 2, 4]] = [99, 88, 77]
print(k) # Output: [99 2 88 4 77]
# 13. Select elements from different rows and columns
l = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
row_indices = [0, 1, 2]
col_indices = [2, 1, 0]
print(l[row_indices, col_indices]) # Output: [30 50 70]
# 14. Repeat elements using fancy indexing
m = np.array([5, 10, 15])
print(m[[1, 1, 1]]) # Output: [10 10 10]
# 15. Select elements using fancy indexing in a flattened array
n = np.array([[10, 20, 30], [40, 50, 60]])
flat_indices = [0, 2, 4]
print(n.flatten()[flat_indices]) # Output: [10 30 50]
# 16. Select elements using negative indices in fancy indexing
o = np.array([100, 200, 300, 400, 500])
print(o[[-1, -3, -5]]) # Output: [500 300 100]
# 17. Assign new values to a 2D array using fancy indexing
p = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row_indices = [0, 2]
col_indices = [1, 2]
p[row_indices, col_indices] = 99
print(p)
# Output: [[ 1 99 3]
# [ 4 5 6]
# [ 7 8 99]]
# 18. Extract a sub-array using fancy indexing
q = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
rows = np.array([0, 1])
cols = np.array([1, 2])
print(q[np.ix_(rows, cols)])
# Output: [[20 30]
# [50 60]]
# 19. Retrieve every alternate row using fancy indexing
r = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(r[[0, 2]])
# Output: [[1 2 3]
# [7 8 9]]
# 20. Select elements by matching a condition using np.where()
s = np.array([10, 20, 30, 40, 50])
print(np.where(s > 25)) # Output: (array([2, 3, 4]),)
import numpy as np
# 1. Transpose a 2D array
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.T)
# Output:
# [[1 4]
# [2 5]
# [3 6]]
# 2. Transpose a 3D array
b = np.arange(12).reshape(2, 3, 2)
print(b.transpose((1, 0, 2)))
# Changes shape from (2, 3, 2) → (3, 2, 2)
# 3. Swap two axes in a 3D array
c = np.arange(12).reshape(2, 3, 2)
print(c.swapaxes(0, 1))
# Changes shape from (2, 3, 2) → (3, 2, 2)
# 4. Swap last two axes of a 3D array
d = np.random.randint(1, 10, (3, 4, 5))
print(d.swapaxes(1, 2).shape)
# Output: (3, 5, 4)
# 5. Swap rows and columns in a 2D array
e = np.array([[1, 2, 3], [4, 5, 6]])
print(e.T)
# Output:
# [[1 4]
# [2 5]
# [3 6]]
# 6. Flatten a transposed matrix
f = np.array([[1, 2, 3], [4, 5, 6]])
print(f.T.flatten()) # Output: [1 4 2 5 3 6]
# 7. Transpose a non-square matrix
g = np.array([[10, 20], [30, 40], [50, 60]])
print(g.T)
# Output:
# [[10 30 50]
# [20 40 60]]
# 8. Transpose a 1D array (no effect)
h = np.array([1, 2, 3])
print(h.T) # Output: [1 2 3]
# 9. Transpose a higher-dimensional array
i = np.random.randint(1, 10, (3, 4, 2))
print(i.transpose((2, 1, 0)).shape)
# Output: (2, 4, 3)
# 10. Swap axes to move the last axis to the front
j = np.random.randint(1, 10, (2, 3, 4))
print(j.swapaxes(0, 2).shape)
# Output: (4, 3, 2)
# 11. Use np.moveaxis to move an axis to a new position
k = np.random.randint(1, 10, (3, 4, 5))
print(np.moveaxis(k, 0, -1).shape)
# Output: (4, 5, 3)
# 12. Transpose a diagonal matrix
l = np.diag([1, 2, 3])
print(l.T)
# Output:
# [[1 0 0]
# [0 2 0]
# [0 0 3]]
# 13. Use np.rollaxis to roll axes forward
m = np.random.randint(1, 10, (3, 4, 5))
print(np.rollaxis(m, 2, 0).shape)
# Output: (5, 3, 4)
# 14. Swap axes and verify if the shape remains unchanged
n = np.random.randint(1, 10, (2, 3, 4))
print(n.swapaxes(1, 2).swapaxes(1, 2).shape == n.shape) # Output: True
# 15. Move multiple axes at once
o = np.random.randint(1, 10, (3, 4, 5))
print(np.moveaxis(o, [0, 1], [-1, -2]).shape)
# Output: (5, 4, 3)
# 16. Swap first and last axes
p = np.random.randint(1, 10, (2, 3, 4))
print(p.swapaxes(0, -1).shape)
# Output: (4, 3, 2)
# 17. Reverse axis order using np.flip
q = np.random.randint(1, 10, (3, 4, 5))
print(np.flip(q, axis=0).shape) # Output: (3, 4, 5)
# 18. Reverse all axes using np.flip
r = np.random.randint(1, 10, (3, 4, 5))
print(np.flip(r).shape) # Output: (3, 4, 5) (same shape, reversed order)
# 19. Swap multiple axes using np.moveaxis
s = np.random.randint(1, 10, (2, 3, 4))
print(np.moveaxis(s, [0, 1, 2], [2, 0, 1]).shape)
# Output: (3, 4, 2)
# 20. Verify if swapping the same axes twice gives the original array
t = np.random.randint(1, 10, (2, 3, 4))
print(np.array_equal(t, t.swapaxes(1, 2).swapaxes(1, 2))) # Output: True
import numpy as np
# 1. Apply np.sqrt on an array
a = np.array([1, 4, 9, 16])
print(np.sqrt(a))
# Output: [1. 2. 3. 4.]
# 2. Apply np.exp on an array
b = np.array([1, 2, 3])
print(np.exp(b))
# Output: [ 2.71828183 7.3890561 20.08553692]
# 3. Compute element-wise maximum
c = np.array([10, 20, 30])
d = np.array([15, 18, 35])
print(np.maximum(c, d))
# Output: [15 20 35]
# 4. Compute element-wise minimum
print(np.minimum(c, d))
# Output: [10 18 30]
# 5. Compute np.mod() (remainder)
e = np.array([5, 9, 15])
f = np.array([2, 4, 7])
print(np.mod(e, f))
# Output: [1 1 1]
# 6. Compute np.power()
g = np.array([2, 3, 4])
h = np.array([3, 2, 1])
print(np.power(g, h))
# Output: [8 9 4]
# 7. Apply np.log10() on an array
i = np.array([10, 100, 1000])
print(np.log10(i))
# Output: [1. 2. 3.]
# 8. Apply np.sign() to check sign of numbers
j = np.array([-5, 0, 7])
print(np.sign(j))
# Output: [-1 0 1]
# 9. Apply np.abs() on negative values
k = np.array([-10, -20, -30])
print(np.abs(k))
# Output: [10 20 30]
# 10. Compute np.ceil() (round up)
l = np.array([1.1, 2.5, 3.7])
print(np.ceil(l))
# Output: [2. 3. 4.]
# 11. Compute np.floor() (round down)
print(np.floor(l))
# Output: [1. 2. 3.]
# 12. Apply np.clip() to limit values
m = np.array([10, 20, 30, 40, 50])
print(np.clip(m, 15, 35))
# Output: [15 20 30 35 35]
# 13. Compute np.rint() (round to nearest integer)
n = np.array([1.49, 2.51, 3.5])
print(np.rint(n))
# Output: [1. 3. 4.]
# 14. Apply np.modf() (split integer and decimal parts)
o = np.array([1.5, 2.3, 3.7])
frac, whole = np.modf(o)
print(frac, whole)
# Output: [0.5 0.3 0.7] [1. 2. 3.]
# 15. Compute np.add() on two arrays
p = np.array([5, 10, 15])
q = np.array([1, 2, 3])
print(np.add(p, q))
# Output: [ 6 12 18]
# 16. Compute np.subtract() on two arrays
print(np.subtract(p, q))
# Output: [ 4 8 12]
# 17. Compute np.multiply() on two arrays
print(np.multiply(p, q))
# Output: [ 5 20 45]
# 18. Compute np.divide() on two arrays
print(np.divide(p, q))
# Output: [5. 5. 5.]
# 19. Compute np.copysign() (copy sign from another array)
r = np.array([-1, -2, -3])
s = np.array([5, 5, -5])
print(np.copysign(r, s))
# Output: [1. 2. -3.]
# 20. Compute np.fmod() (element-wise remainder, like mod but keeps sign of
numerator)
t = np.array([10, 20, -30])
u = np.array([3, 4, 7])
print(np.fmod(t, u))
# Output: [ 1 0 -2]
import numpy as np
# 1. Compute element-wise square of a NumPy array
a = np.array([2, 3, 4])
print(a ** 2)
# Output: [ 4 9 16]
# 2. Compute reciprocal of an array using element-wise division
b = np.array([2.0, 4.0, 8.0])
print(1 / b)
# Output: [0.5 0.25 0.125]
# 3. Apply a mathematical expression element-wise
c = np.array([1, 2, 3])
d = np.array([4, 5, 6])
print((c * 2 + d) / 3)
# Output: [2. 3. 4.]
# 4. Convert a Celsius array to Fahrenheit using vectorized operations
celsius = np.array([0, 20, 100])
fahrenheit = celsius * 9/5 + 32
print(fahrenheit)
# Output: [ 32. 68. 212.]
# 5. Compute exponential moving average with a decay factor
x = np.array([1, 2, 3, 4])
alpha = 0.5
ema = np.cumsum(alpha * x)
print(ema)
# Output: [0.5 1.5 3.0 5.0]
# 6. Compute distance between two points (vectorized Euclidean distance)
p1 = np.array([1, 2])
p2 = np.array([4, 6])
distance = np.sqrt(np.sum((p1 - p2) ** 2))
print(distance)
# Output: 5.0
# 7. Use broadcasting to scale a matrix
matrix = np.array([[1, 2], [3, 4]])
scalar = 10
print(matrix * scalar)
# Output:
# [[10 20]
# [30 40]]
# 8. Compute dot product of two vectors
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
print(np.dot(v1, v2))
# Output: 32
# 9. Compute matrix multiplication using @ operator
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B)
# Output:
# [[19 22]
# [43 50]]
# 10. Create an array using linspace and apply element-wise function
x = np.linspace(0, 10, 5)
print(np.sin(x))
# Output: [ 0. 0.70710678 1. 0.70710678 0. ]
# 11. Compute outer product of two vectors
v3 = np.array([1, 2, 3])
v4 = np.array([4, 5])
print(np.outer(v3, v4))
# Output:
# [[ 4 5]
# [ 8 10]
# [12 15]]
# 12. Use np.where() to replace negative values with zero
arr = np.array([-1, 2, -3, 4])
print(np.where(arr < 0, 0, arr))
# Output: [0 2 0 4]
# 13. Compute row-wise sum of a 2D array
M = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(M, axis=1))
# Output: [ 6 15]
# 14. Compute column-wise maximum of a 2D array
print(np.max(M, axis=0))
# Output: [4 5 6]
# 15. Normalize a 1D array (min-max scaling)
arr = np.array([10, 20, 30])
normalized = (arr - np.min(arr)) / (np.max(arr) - np.min(arr))
print(normalized)
# Output: [0. 0.5 1.]
# 16. Compute cosine similarity between two vectors
vec1 = np.array([1, 2, 3])
vec2 = np.array([4, 5, 6])
cosine_sim = np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
print(cosine_sim)
# Output: 0.9746318461970762
# 17. Vectorized implementation of a sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
data = np.array([-1, 0, 1])
print(sigmoid(data))
# Output: [0.26894142 0.5 0.73105858]
# 18. Compute element-wise reciprocal of square root
arr = np.array([4, 9, 16])
print(1 / np.sqrt(arr))
# Output: [0.5 0.33333333 0.25]
# 19. Compute moving average using convolution
arr = np.array([1, 2, 3, 4, 5])
kernel = np.ones(3) / 3
print(np.convolve(arr, kernel, mode='valid'))
# Output: [2. 3. 4.]
# 20. Compute variance of an array
arr = np.array([1, 2, 3, 4, 5])
print(np.var(arr))
# Output: 2.0
import numpy as np
# 1. Replace negative values with zero using np.where()
arr1 = np.array([-5, 10, -3, 8])
print(np.where(arr1 < 0, 0, arr1))
# Output: [ 0 10 0 8]
# 2. Convert temperatures from Celsius to Fahrenheit only if above freezing
temps = np.array([-10, 0, 15, 30])
fahrenheit = np.where(temps > 0, temps * 9/5 + 32, temps)
print(fahrenheit)
# Output: [-10. 0. 59. 86.]
# 3. Assign a category based on values
grades = np.array([45, 67, 89, 92])
categories = np.where(grades >= 90, "A", np.where(grades >= 70, "B", "C"))
print(categories)
# Output: ['C' 'C' 'B' 'A']
# 4. Replace all even numbers with their negative values
arr2 = np.array([2, 3, 4, 5, 6])
print(np.where(arr2 % 2 == 0, -arr2, arr2))
# Output: [-2 3 -4 5 -6]
# 5. Set elements to NaN if they are negative
arr3 = np.array([-2, 5, -7, 10], dtype=float)
print(np.where(arr3 < 0, np.nan, arr3))
# Output: [nan 5. nan 10.]
# 6. Replace values less than 5 with half their values
arr4 = np.array([1, 3, 5, 7])
print(np.where(arr4 < 5, arr4 / 2, arr4))
# Output: [0.5 1.5 5. 7. ]
# 7. Assign labels based on conditions
numbers = np.array([10, 20, 30, 40])
labels = np.where(numbers < 20, "Low", np.where(numbers < 35, "Medium",
"High"))
print(labels)
# Output: ['Low' 'Medium' 'Medium' 'High']
# 8. Convert all negative numbers to absolute values
arr5 = np.array([-1, -5, 10, -15])
print(np.abs(arr5))
# Output: [ 1 5 10 15]
# 9. Compute element-wise maximum between two arrays
arr6 = np.array([10, 15, 20])
arr7 = np.array([12, 14, 22])
print(np.maximum(arr6, arr7))
# Output: [12 15 22]
# 10. Set all values greater than the mean to 1, others to 0
arr8 = np.array([5, 10, 15, 20])
mean_val = np.mean(arr8)
print(np.where(arr8 > mean_val, 1, 0))
# Output: [0 0 1 1]
# 11. Clip array values between 10 and 50
arr9 = np.array([5, 20, 50, 100])
print(np.clip(arr9, 10, 50))
# Output: [10 20 50 50]
# 12. Compute piecewise function f(x) = x^2 if x > 0, else -x
arr10 = np.array([-3, -2, 0, 1, 2])
print(np.where(arr10 > 0, arr10 ** 2, -arr10))
# Output: [3 2 0 1 4]
# 13. Convert all odd numbers to 0 and even numbers to 1
arr11 = np.array([3, 6, 9, 12])
print(np.where(arr11 % 2 == 0, 1, 0))
# Output: [0 1 0 1]
# 14. Scale numbers between 0 and 1 using min-max normalization
arr12 = np.array([10, 20, 30, 40])
normalized = (arr12 - np.min(arr12)) / (np.max(arr12) - np.min(arr12))
print(normalized)
# Output: [0. 0.333 0.667 1. ]
# 15. Categorize array elements into bins
arr13 = np.array([10, 30, 50, 70])
bins = np.digitize(arr13, bins=[20, 40, 60])
print(bins)
# Output: [0 1 2 3]
# 16. Convert binary values (1s and 0s) to boolean
binary_arr = np.array([0, 1, 0, 1])
bool_arr = binary_arr.astype(bool)
print(bool_arr)
# Output: [False True False True]
# 17. Replace all values greater than median with median
arr14 = np.array([2, 4, 6, 8, 10])
median_val = np.median(arr14)
print(np.where(arr14 > median_val, median_val, arr14))
# Output: [ 2 4 6 6 6]
# 18. Apply conditional operation to reshape an array
arr15 = np.array([[1, 2, 3], [4, 5, 6]])
print(np.where(arr15 % 2 == 0, arr15 * 2, arr15))
# Output:
# [[ 1 4 3]
# [ 8 5 12]]
# 19. Replace values below 25th percentile with 0
arr16 = np.array([10, 20, 30, 40])
percentile_25 = np.percentile(arr16, 25)
print(np.where(arr16 < percentile_25, 0, arr16))
# Output: [ 0 20 30 40]
# 20. Compute softmax function using NumPy
def softmax(x):
exp_x = np.exp(x - np.max(x)) # Subtract max for numerical stability
return exp_x / np.sum(exp_x)
arr17 = np.array([2.0, 1.0, 0.1])
print(softmax(arr17))
# Output: [0.659 0.242 0.099]
import numpy as np
# 1. Compute the mean of an array
arr1 = np.array([10, 20, 30, 40])
print(np.mean(arr1))
# Output: 25.0
# 2. Compute the median of an array
print(np.median(arr1))
# Output: 25.0
# 3. Compute the variance of an array
print(np.var(arr1))
# Output: 125.0
# 4. Compute the standard deviation of an array
print(np.std(arr1))
# Output: 11.1803
# 5. Compute cumulative sum of an array
arr2 = np.array([1, 2, 3, 4])
print(np.cumsum(arr2))
# Output: [ 1 3 6 10]
# 6. Compute cumulative product of an array
print(np.cumprod(arr2))
# Output: [ 1 2 6 24]
# 7. Compute row-wise mean of a 2D array
arr3 = np.array([[1, 2, 3], [4, 5, 6]])
print(np.mean(arr3, axis=1))
# Output: [2. 5.]
# 8. Compute column-wise sum of a 2D array
print(np.sum(arr3, axis=0))
# Output: [5 7 9]
# 9. Compute maximum and minimum values of an array
arr4 = np.array([3, 7, 1, 9])
print(np.max(arr4), np.min(arr4))
# Output: 9 1
# 10. Compute mode of an array using NumPy
from scipy import stats
arr5 = np.array([1, 2, 2, 3, 3, 3, 4])
print(stats.mode(arr5, keepdims=True)[0])
# Output: [3]
# 11. Compute Pearson correlation coefficient between two arrays
arr6 = np.array([1, 2, 3, 4])
arr7 = np.array([2, 4, 6, 8])
print(np.corrcoef(arr6, arr7)[0, 1])
# Output: 1.0
# 12. Compute Spearman rank correlation between two arrays
from scipy.stats import spearmanr
print(spearmanr(arr6, arr7).correlation)
# Output: 1.0
# 13. Compute row-wise variance of a 2D array
arr8 = np.array([[10, 20, 30], [40, 50, 60]])
print(np.var(arr8, axis=1))
# Output: [66.66666667 66.66666667]
# 14. Compute moving average using convolution
arr9 = np.array([1, 2, 3, 4, 5])
kernel = np.ones(3) / 3
print(np.convolve(arr9, kernel, mode='valid'))
# Output: [2. 3. 4.]
# 15. Compute weighted average of an array
values = np.array([10, 20, 30])
weights = np.array([0.2, 0.5, 0.3])
print(np.average(values, weights=weights))
# Output: 22.0
# 16. Compute interquartile range (IQR) of an array
q75, q25 = np.percentile(arr10 := np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]), [75, 25])
print(q75 - q25)
# Output: 4.0
# 17. Compute element-wise logarithm with base 10
arr11 = np.array([1, 10, 100])
print(np.log10(arr11))
# Output: [0. 1. 2.]
# 18. Compute exponential of each element in an array
arr12 = np.array([1, 2, 3])
print(np.exp(arr12))
# Output: [ 2.71828183 7.3890561 20.08553692]
# 19. Compute coefficient of variation (CV) of an array
arr13 = np.array([10, 20, 30])
cv = np.std(arr13) / np.mean(arr13)
print(cv)
# Output: 0.408
# 20. Normalize an array using Z-score normalization
arr14 = np.array([1, 2, 3, 4, 5])
z_scores = (arr14 - np.mean(arr14)) / np.std(arr14)
print(z_scores)
# Output: [-1.26491106 -0.63245553 0. 0.63245553 1.26491106]
import numpy as np
# 1. Count the number of True values in a boolean array
bool_arr1 = np.array([True, False, True, True, False])
print(np.sum(bool_arr1))
# Output: 3
# 2. Check if all elements in an array are True
print(np.all(bool_arr1))
# Output: False
# 3. Check if any element in an array is True
print(np.any(bool_arr1))
# Output: True
# 4. Find indices of True values in a boolean array
print(np.where(bool_arr1))
# Output: (array([0, 2, 3]),)
# 5. Count the number of False values in a boolean array
print(np.sum(~bool_arr1))
# Output: 2
# 6. Convert an integer array to boolean (0 → False, others → True)
arr1 = np.array([0, 1, 2, 0, 5])
bool_arr2 = arr1.astype(bool)
print(bool_arr2)
# Output: [False True True False True]
# 7. Replace all False values with NaN in a float array
arr2 = np.array([1.2, 0.0, 3.4, 0.0, 5.6])
bool_mask = arr2 > 0
print(np.where(bool_mask, arr2, np.nan))
# Output: [1.2 nan 3.4 nan 5.6]
# 8. Extract all True values from an array
bool_arr3 = np.array([True, False, True, False, True])
arr3 = np.array([10, 20, 30, 40, 50])
print(arr3[bool_arr3])
# Output: [10 30 50]
# 9. Invert a boolean array (True → False, False → True)
print(np.logical_not(bool_arr1))
# Output: [False True False False True]
# 10. Check if two boolean arrays are equal
bool_arr4 = np.array([True, False, True, False])
bool_arr5 = np.array([True, False, False, False])
print(np.array_equal(bool_arr4, bool_arr5))
# Output: False
# 11. Find the first occurrence of True in a boolean array
print(np.argmax(bool_arr1))
# Output: 0 (Index of first True)
# 12. Compute logical AND between two boolean arrays
bool_arr6 = np.array([True, False, True])
bool_arr7 = np.array([False, False, True])
print(np.logical_and(bool_arr6, bool_arr7))
# Output: [False False True]
# 13. Compute logical OR between two boolean arrays
print(np.logical_or(bool_arr6, bool_arr7))
# Output: [ True False True]
# 14. Compute logical XOR between two boolean arrays
print(np.logical_xor(bool_arr6, bool_arr7))
# Output: [ True False False]
# 15. Create a boolean mask for elements greater than the mean
arr4 = np.array([10, 20, 30, 40, 50])
mean_val = np.mean(arr4)
bool_mask2 = arr4 > mean_val
print(bool_mask2)
# Output: [False False False True True]
# 16. Replace all elements below a threshold with zero
arr5 = np.array([5, 15, 25, 35])
threshold = 20
print(np.where(arr5 < threshold, 0, arr5))
# Output: [ 0 0 25 35]
# 17. Find the percentage of True values in a boolean array
bool_arr8 = np.array([True, False, True, True, False, True])
percentage_true = np.mean(bool_arr8) * 100
print(percentage_true)
# Output: 66.66666666666666
# 18. Use boolean indexing to replace all True values with -1
arr6 = np.array([1, 2, 3, 4, 5])
bool_mask3 = arr6 > 2
arr6[bool_mask3] = -1
print(arr6)
# Output: [ 1 2 -1 -1 -1]
# 19. Filter out elements that are not within a given range
arr7 = np.array([5, 10, 15, 20, 25])
range_mask = (arr7 >= 10) & (arr7 <= 20)
print(arr7[range_mask])
# Output: [10 15 20]
# 20. Create a boolean mask for prime numbers in an array
def is_prime(n):
if n < 2:
return False
for i in range(2, int(np.sqrt(n)) + 1):
if n % i == 0:
return False
return True
arr8 = np.array([2, 3, 4, 5, 6, 7, 8, 9])
prime_mask = np.vectorize(is_prime)(arr8)
print(prime_mask)
# Output: [ True True False True False True False False]
import numpy as np
# 1. Sort a 1D NumPy array in ascending order
arr1 = np.array([5, 3, 8, 1, 9])
print(np.sort(arr1))
# Output: [1 3 5 8 9]
# 2. Sort a 1D NumPy array in descending order
print(np.sort(arr1)[::-1])
# Output: [9 8 5 3 1]
# 3. Get the indices that would sort the array
print(np.argsort(arr1))
# Output: [3 1 0 2 4]
# 4. Sort a 2D NumPy array along rows
arr2 = np.array([[3, 2, 1], [9, 7, 8]])
print(np.sort(arr2, axis=1))
# Output: [[1 2 3]
# [7 8 9]]
# 5. Sort a 2D NumPy array along columns
print(np.sort(arr2, axis=0))
# Output: [[3 2 1]
# [9 7 8]]
# 6. Get the indices that would sort a 2D array row-wise
print(np.argsort(arr2, axis=1))
# Output: [[2 1 0]
# [1 2 0]]
# 7. Get the top 3 smallest values from an array
arr3 = np.array([10, 20, 5, 8, 2])
print(np.sort(arr3)[:3])
# Output: [2 5 8]
# 8. Get the top 3 largest values from an array
print(np.sort(arr3)[-3:])
# Output: [10 20 20]
# 9. Find the k-th smallest element in an array (k=2)
k=2
print(np.partition(arr3, k-1)[k-1])
# Output: 5
# 10. Find the k-th largest element in an array (k=2)
print(np.partition(arr3, -k)[-k])
# Output: 10
# 11. Perform an indirect stable sort
arr4 = np.array([3, 1, 2, 1])
print(np.argsort(arr4, kind="stable"))
# Output: [1 3 2 0]
# 12. Sort an array in-place
arr5 = np.array([10, 5, 3, 8])
arr5.sort()
print(arr5)
# Output: [3 5 8 10]
# 13. Sort a structured array by a specific field
dtype = [('name', 'U10'), ('age', int)]
arr6 = np.array([('Alice', 25), ('Bob', 30), ('Charlie', 22)], dtype=dtype)
print(np.sort(arr6, order='age'))
# Output: [('Charlie', 22) ('Alice', 25) ('Bob', 30)]
# 14. Sort an array using mergesort algorithm
print(np.sort(arr1, kind='mergesort'))
# Output: [1 3 5 8 9]
# 15. Sort an array using quicksort algorithm
print(np.sort(arr1, kind='quicksort'))
# Output: [1 3 5 8 9]
# 16. Find the sorted unique elements in an array
arr7 = np.array([5, 2, 3, 5, 2, 8, 8, 3])
print(np.unique(arr7))
# Output: [2 3 5 8]
# 17. Sort an array of strings
arr8 = np.array(["banana", "apple", "cherry", "date"])
print(np.sort(arr8))
# Output: ['apple' 'banana' 'cherry' 'date']
# 18. Get indices to sort an array of strings
print(np.argsort(arr8))
# Output: [1 0 2 3]
# 19. Use lexsort to sort by multiple keys
names = np.array(["John", "Alice", "Bob"])
ages = np.array([25, 30, 22])
sorted_indices = np.lexsort((ages, names))
print(names[sorted_indices], ages[sorted_indices])
# Output: ['Alice' 'Bob' 'John'] [30 22 25]
# 20. Sort a boolean array
bool_arr = np.array([True, False, True, False])
print(np.sort(bool_arr))
# Output: [False False True True]
import numpy as np
# 1. Find unique elements in an array
arr1 = np.array([3, 7, 3, 7, 2, 1, 9])
print(np.unique(arr1))
# Output: [1 2 3 7 9]
# 2. Find unique elements and their counts
unique_elements, counts = np.unique(arr1, return_counts=True)
print(unique_elements, counts)
# Output: [1 2 3 7 9] [1 1 2 2 1]
# 3. Check if elements of one array exist in another
arr2 = np.array([3, 7, 10])
print(np.isin(arr2, arr1))
# Output: [ True True False]
# 4. Find elements that are in arr1 but not in arr2
print(np.setdiff1d(arr1, arr2))
# Output: [1 2 9]
# 5. Find elements common in both arrays
print(np.intersect1d(arr1, arr2))
# Output: [3 7]
# 6. Find elements that are in either of the arrays but not both (symmetric
difference)
print(np.setxor1d(arr1, arr2))
# Output: [ 1 2 9 10]
# 7. Find the union of two arrays
print(np.union1d(arr1, arr2))
# Output: [ 1 2 3 7 9 10]
# 8. Find indices where elements of arr2 appear in arr1
print(np.searchsorted(np.sort(arr1), arr2))
# Output: [2 3 5]
# 9. Check if two arrays contain the same elements (ignoring order)
arr3 = np.array([1, 2, 3])
arr4 = np.array([3, 2, 1])
print(np.array_equal(np.sort(arr3), np.sort(arr4)))
# Output: True
# 10. Find repeated values in an array
arr5 = np.array([5, 1, 5, 2, 1, 7, 7])
print(arr5[np.where(np.bincount(arr5) > 1)])
# Output: [5 1 7]
# 11. Count how many times each element appears
unique_vals, counts = np.unique(arr5, return_counts=True)
print(dict(zip(unique_vals, counts)))
# Output: {1: 2, 2: 1, 5: 2, 7: 2}
# 12. Find the most frequent element
most_frequent = unique_vals[np.argmax(counts)]
print(most_frequent)
# Output: 5 (or another most frequent element)
# 13. Remove duplicates from an array while maintaining order
arr6 = np.array([4, 2, 4, 3, 2, 1])
_, indices = np.unique(arr6, return_index=True)
print(arr6[np.sort(indices)])
# Output: [4 2 3 1]
# 14. Find missing numbers from a range
arr7 = np.array([1, 3, 5, 7])
print(np.setdiff1d(np.arange(1, 8), arr7))
# Output: [2 4 6]
# 15. Get a boolean mask of common elements
mask = np.in1d(arr1, arr2)
print(mask)
# Output: [ True True False False False False True]
# 16. Find duplicates in an array
duplicates = arr5[counts > 1]
print(duplicates)
# Output: [1 5 7]
# 17. Remove all occurrences of a specific value
arr8 = np.array([1, 2, 3, 2, 4, 2, 5])
arr8 = arr8[arr8 != 2]
print(arr8)
# Output: [1 3 4 5]
# 18. Find unique pairs of numbers from two arrays
arr9 = np.array([1, 2, 3])
arr10 = np.array([4, 5])
print(np.array(np.meshgrid(arr9, arr10)).T.reshape(-1, 2))
# Output: [[1 4] [1 5] [2 4] [2 5] [3 4] [3 5]]
# 19. Find common elements between three arrays
arr11 = np.array([1, 2, 3, 4])
arr12 = np.array([2, 3, 5])
arr13 = np.array([3, 6, 2])
print(np.intersect1d(np.intersect1d(arr11, arr12), arr13))
# Output: [2 3]
# 20. Find unique elements that appear only once in an array
unique_once = unique_vals[counts == 1]
print(unique_once)
# Output: [2]
import numpy as np
# 1. Save a NumPy array to a .npy file and load it back
arr1 = np.array([1, 2, 3, 4, 5])
np.save('array.npy', arr1)
loaded_arr1 = np.load('array.npy')
print(loaded_arr1)
# Output: [1 2 3 4 5]
# 2. Save multiple arrays into a single .npz file and load them
arr2 = np.array([10, 20, 30])
arr3 = np.array([[1, 2], [3, 4]])
np.savez('arrays.npz', a=arr1, b=arr2, c=arr3)
loaded = np.load('arrays.npz')
print(loaded['a'], loaded['b'], loaded['c'])
# Output: [1 2 3 4 5] [10 20 30] [[1 2] [3 4]]
# 3. Save an array to a text file and load it back
np.savetxt('array.txt', arr1, delimiter=',')
loaded_arr2 = np.loadtxt('array.txt', delimiter=',')
print(loaded_arr2)
# Output: [1. 2. 3. 4. 5.]
# 4. Save a 2D array to a CSV file and read it back
arr4 = np.array([[5, 10, 15], [20, 25, 30]])
np.savetxt('array.csv', arr4, delimiter=',', fmt='%d')
loaded_arr3 = np.loadtxt('array.csv', delimiter=',', dtype=int)
print(loaded_arr3)
# Output: [[ 5 10 15] [20 25 30]]
# 5. Save and load a structured array
dtype = [('name', 'U10'), ('age', int)]
data = np.array([('Alice', 25), ('Bob', 30)], dtype=dtype)
np.savetxt('structured.csv', data, fmt='%s', delimiter=',')
loaded_data = np.genfromtxt('structured.csv', delimiter=',', dtype=dtype)
print(loaded_data)
# Output: [('Alice', 25) ('Bob', 30)]
# 6. Append new data to an existing text file
with open('array.txt', 'a') as f:
np.savetxt(f, [6, 7, 8], delimiter=',')
loaded_arr4 = np.loadtxt('array.txt', delimiter=',')
print(loaded_arr4)
# Output: [1. 2. 3. 4. 5. 6. 7. 8.]
# 7. Save an array with scientific notation formatting
arr5 = np.array([0.000123, 0.000456])
np.savetxt('scientific.txt', arr5, fmt='%.6e')
loaded_arr5 = np.loadtxt('scientific.txt')
print(loaded_arr5)
# Output: [1.23e-04 4.56e-04]
# 8. Load a CSV file with missing values
arr6 = np.genfromtxt('array.csv', delimiter=',', filling_values=-1)
print(arr6)
# Output: (Handles missing values by replacing them with -1)
# 9. Save and load a boolean array
bool_arr = np.array([True, False, True])
np.save('bool_array.npy', bool_arr)
loaded_bool = np.load('bool_array.npy')
print(loaded_bool)
# Output: [ True False True]
# 10. Save a complex number array and load it
complex_arr = np.array([1+2j, 3+4j])
np.save('complex.npy', complex_arr)
loaded_complex = np.load('complex.npy')
print(loaded_complex)
# Output: [1.+2.j 3.+4.j]
# 11. Save an array with a header and footer
np.savetxt('header_footer.txt', arr1, header='My Array', footer='End of File')
with open('header_footer.txt') as f:
print(f.read())
# Output: My Array (array data) End of File
# 12. Save an array with tab-separated values
np.savetxt('tab_separated.txt', arr1, delimiter='\t')
loaded_arr6 = np.loadtxt('tab_separated.txt', delimiter='\t')
print(loaded_arr6)
# Output: [1. 2. 3. 4. 5.]
# 13. Save an array using a custom format string
np.savetxt('custom_format.txt', arr1, fmt='%04d')
with open('custom_format.txt') as f:
print(f.read())
# Output: 0001 0002 0003 0004 0005
# 14. Save an array with column names
header = 'Column1,Column2,Column3'
np.savetxt('named_columns.csv', arr4, delimiter=',', header=header,
comments='')
loaded_arr7 = np.loadtxt('named_columns.csv', delimiter=',', skiprows=1)
print(loaded_arr7)
# Output: [[ 5 10 15] [20 25 30]]
# 15. Load a file where data is separated by different delimiters (space and
comma)
data_str = "1,2 3,4 5"
np.savetxt('mixed_delimiters.txt', [data_str], fmt='%s')
with open('mixed_delimiters.txt') as f:
print(f.read())
# Output: 1,2 3,4 5 (needs manual parsing)
# 16. Load only a specific column from a text file
np.savetxt('multi_column.txt', np.random.rand(5, 3), delimiter=',')
loaded_col = np.loadtxt('multi_column.txt', delimiter=',', usecols=(1,))
print(loaded_col)
# Output: [random numbers from column 1]
# 17. Save a matrix in row-major order and load it back
matrix = np.array([[1, 2, 3], [4, 5, 6]])
np.save('matrix.npy', matrix)
loaded_matrix = np.load('matrix.npy')
print(loaded_matrix)
# Output: [[1 2 3] [4 5 6]]
# 18. Save an array without scientific notation
np.savetxt('no_sci_notation.txt', arr5, fmt='%f')
with open('no_sci_notation.txt') as f:
print(f.read())
# Output: 0.000123 0.000456
# 19. Read a file that contains both numbers and text
np.savetxt('mixed_data.txt', [('Alice', 25), ('Bob', 30)], fmt='%s', delimiter=',')
loaded_mixed = np.genfromtxt('mixed_data.txt', delimiter=',', dtype=None,
encoding=None)
print(loaded_mixed)
# Output: [('Alice', '25') ('Bob', '30')]
# 20. Save a 3D array and load it back
arr3D = np.random.rand(2, 2, 2)
np.save('array3D.npy', arr3D)
loaded_3D = np.load('array3D.npy')
print(loaded_3D.shape)
# Output: (2, 2, 2)
import numpy as np
# 1. Create a 3x3 identity matrix
I = np.eye(3)
print(I)
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
# 2. Compute the inverse of a matrix
A = np.array([[3, 2], [1, 4]])
A_inv = np.linalg.inv(A)
print(A_inv)
# Output: [[ 0.4 -0.2]
# [-0.1 0.3]]
# 3. Compute the determinant of a matrix
det_A = np.linalg.det(A)
print(det_A)
# Output: 10.0
# 4. Solve a system of linear equations: Ax = b
b = np.array([5, 6])
x = np.linalg.solve(A, b)
print(x)
# Output: [1.4 1.2]
# 5. Compute the eigenvalues of a matrix
eig_vals, eig_vecs = np.linalg.eig(A)
print(eig_vals)
# Output: [2.618 4.382]
# 6. Compute the eigenvectors of a matrix
print(eig_vecs)
# Output: Eigenvectors of A
# 7. Compute the rank of a matrix
rank_A = np.linalg.matrix_rank(A)
print(rank_A)
# Output: 2
# 8. Compute the Frobenius norm of a matrix
norm_A = np.linalg.norm(A, 'fro')
print(norm_A)
# Output: sqrt(3² + 2² + 1² + 4²) = 5.477
# 9. Compute the singular value decomposition (SVD)
U, S, Vt = np.linalg.svd(A)
print(U, S, Vt)
# Output: SVD components of A
# 10. Compute the Moore-Penrose pseudo-inverse
A_pinv = np.linalg.pinv(A)
print(A_pinv)
# Output: [[ 0.4 -0.2]
# [-0.1 0.3]]
# 11. Check if a matrix is orthogonal
Q = np.array([[0, 1], [-1, 0]])
print(np.allclose(np.dot(Q.T, Q), np.eye(2)))
# Output: True
# 12. Compute the trace of a matrix
trace_A = np.trace(A)
print(trace_A)
# Output: 7
# 13. Compute the dot product of two vectors
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
dot_product = np.dot(v1, v2)
print(dot_product)
# Output: 32
# 14. Compute the cross product of two vectors
cross_product = np.cross(v1, v2)
print(cross_product)
# Output: [-3 6 -3]
# 15. Compute the outer product of two vectors
outer_product = np.outer(v1, v2)
print(outer_product)
# Output:
# [[ 4 5 6]
# [ 8 10 12]
# [12 15 18]]
# 16. Compute the projection of a vector onto another vector
v_proj = (np.dot(v1, v2) / np.dot(v2, v2)) * v2
print(v_proj)
# Output: [1.92 2.4 2.88]
# 17. Find the least squares solution to Ax = b
A_ls = np.array([[2, 3], [3, 5], [5, 8]])
b_ls = np.array([5, 8, 13])
x_ls, _, _, _ = np.linalg.lstsq(A_ls, b_ls, rcond=None)
print(x_ls)
# Output: Least squares solution
# 18. Compute the Gram-Schmidt orthogonalization
def gram_schmidt(X):
Q, _ = np.linalg.qr(X)
return Q
X = np.array([[1, 1], [1, -1]])
Q = gram_schmidt(X)
print(Q)
# Output: Orthogonal matrix
# 19. Compute the covariance matrix of a dataset
data = np.array([[2, 3, 4], [5, 6, 7]])
cov_matrix = np.cov(data)
print(cov_matrix)
# Output: Covariance matrix
# 20. Compute the Cholesky decomposition of a positive-definite matrix
M = np.array([[4, 2], [2, 3]])
L = np.linalg.cholesky(M)
print(L)
# Output:
# [[2. 0. ]
# [1. 1.41]]
import numpy as np
# 1. Generate a random integer between 10 and 50 (inclusive)
rand_int = np.random.randint(10, 51)
print(rand_int)
# Output: A random integer in [10, 50]
# 2. Generate a 3x3 matrix of random floats between 0 and 1
rand_matrix = np.random.rand(3, 3)
print(rand_matrix)
# Output: A 3x3 matrix with values between 0 and 1
# 3. Generate a 1D array of 5 random numbers from a normal distribution
(mean=0, std=1)
rand_norm = np.random.randn(5)
print(rand_norm)
# Output: Array of 5 normally distributed numbers
# 4. Generate 10 random numbers from a uniform distribution between -1 and 1
rand_uniform = np.random.uniform(-1, 1, 10)
print(rand_uniform)
# Output: Array of 10 values in range [-1, 1]
# 5. Generate a random 4x4 matrix of integers between 100 and 200
rand_int_matrix = np.random.randint(100, 200, (4, 4))
print(rand_int_matrix)
# Output: 4x4 matrix with values between 100 and 200
# 6. Shuffle an array in-place
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr)
# Output: A shuffled version of [1, 2, 3, 4, 5]
# 7. Select a random sample of 3 elements from an array without replacement
sample = np.random.choice(arr, 3, replace=False)
print(sample)
# Output: 3 unique values from arr
# 8. Generate a random permutation of numbers from 0 to 9
perm = np.random.permutation(10)
print(perm)
# Output: A random permutation of [0,1,2,3,4,5,6,7,8,9]
# 9. Generate a 5x5 matrix of random values from an exponential distribution
(lambda=1)
rand_exp = np.random.exponential(scale=1, size=(5, 5))
print(rand_exp)
# Output: 5x5 matrix from exponential distribution
# 10. Generate 7 random values from a Poisson distribution (lambda=3)
rand_poisson = np.random.poisson(3, 7)
print(rand_poisson)
# Output: Array of 7 values from a Poisson distribution
# 11. Generate 6 random values from a binomial distribution (n=10, p=0.5)
rand_binomial = np.random.binomial(10, 0.5, 6)
print(rand_binomial)
# Output: Array of 6 values from binomial distribution
# 12. Generate a 2D array with normally distributed values (mean=5, std=2)
rand_norm_2D = np.random.normal(5, 2, (3, 3))
print(rand_norm_2D)
# Output: 3x3 matrix of normal distribution values
# 13. Generate a random 2x3 matrix with values from a standard normal
distribution
rand_std_norm = np.random.standard_normal((2, 3))
print(rand_std_norm)
# Output: 2x3 matrix with values from standard normal distribution
# 14. Generate a 5x5 matrix of random numbers in range [0, 1) and set a seed for
reproducibility
np.random.seed(42)
rand_fixed = np.random.rand(5, 5)
print(rand_fixed)
# Output: Same matrix every time seed=42 is set
# 15. Draw 8 samples from a geometric distribution (p=0.3)
rand_geometric = np.random.geometric(0.3, 8)
print(rand_geometric)
# Output: 8 values from geometric distribution
# 16. Generate a random integer between 1 and 10 (inclusive) with a given
probability distribution
values = np.arange(1, 11)
probabilities = np.linspace(0.01, 0.1, 10)
rand_weighted = np.random.choice(values, p=probabilities/sum(probabilities))
print(rand_weighted)
# Output: A random integer between 1 and 10 with given probabilities
# 17. Generate a 1D array of 6 random integers between 1 and 100 (inclusive)
without replacement
rand_unique = np.random.choice(np.arange(1, 101), size=6, replace=False)
print(rand_unique)
# Output: 6 unique numbers between 1 and 100
# 18. Generate a 3x3 correlation matrix using random values
random_matrix = np.random.rand(3, 3)
corr_matrix = np.corrcoef(random_matrix)
print(corr_matrix)
# Output: 3x3 correlation matrix
# 19. Generate a set of random floating-point numbers, round them to 2 decimal
places
rand_floats = np.round(np.random.rand(5), 2)
print(rand_floats)
# Output: Array of 5 numbers rounded to 2 decimal places
# 20. Generate a dataset of 1000 random values and calculate their mean and
variance
dataset = np.random.randn(1000)
mean_value = np.mean(dataset)
variance_value = np.var(dataset)
print(f"Mean: {mean_value}, Variance: {variance_value}")
# Output: Mean and variance of 1000 random values
import numpy as np
# 1. Simulate a 1D random walk of 1000 steps
steps = np.random.choice([-1, 1], size=1000)
position = np.cumsum(steps)
print(position)
# Output: Array of positions after each step
# 2. Find the farthest point from the origin in the random walk
farthest_point = np.max(np.abs(position))
print(farthest_point)
# Output: Maximum absolute displacement
# 3. Count how many times the walk crosses zero
crossings = np.sum(np.diff(np.sign(position)) != 0)
print(crossings)
# Output: Number of zero crossings
# 4. Simulate 5 independent 1D random walks of 500 steps each
walks = np.cumsum(np.random.choice([-1, 1], size=(500, 5)), axis=0)
print(walks)
# Output: 500x5 array representing five random walks
# 5. Find the final positions of 10 independent 1D random walks of 1000 steps
final_positions = np.cumsum(np.random.choice([-1, 1], size=(1000, 10)),
axis=0)[-1]
print(final_positions)
# Output: Array of final positions for 10 walks
# 6. Simulate a 2D random walk of 500 steps
x_steps = np.random.choice([-1, 1], size=500)
y_steps = np.random.choice([-1, 1], size=500)
x_position = np.cumsum(x_steps)
y_position = np.cumsum(y_steps)
print(x_position, y_position)
# Output: X and Y positions after each step
# 7. Compute the Euclidean distance from the origin at the final step of a 2D
walk
final_distance = np.sqrt(x_position[-1]**2 + y_position[-1]**2)
print(final_distance)
# Output: Distance from origin at final step
# 8. Simulate a biased 1D random walk where +1 has a 70% probability
biased_steps = np.random.choice([-1, 1], size=1000, p=[0.3, 0.7])
biased_position = np.cumsum(biased_steps)
print(biased_position)
# Output: Biased walk positions
# 9. Find the first time the walk crosses 10 in positive direction
first_crossing = np.where(position >= 10)[0][0] if np.any(position >= 10) else -1
print(first_crossing)
# Output: Index of first crossing or -1 if never crossed
# 10. Generate a 3D random walk of 500 steps
z_steps = np.random.choice([-1, 1], size=500)
z_position = np.cumsum(z_steps)
print(z_position)
# Output: Array of Z positions
# 11. Compute the maximum distance from the origin at any step in a 2D random
walk
max_distance = np.max(np.sqrt(x_position**2 + y_position**2))
print(max_distance)
# Output: Maximum distance from origin
# 12. Simulate 1000 random walks of 500 steps and count how many end at 0
num_walks = 1000
walks = np.cumsum(np.random.choice([-1, 1], size=(500, num_walks)), axis=0)
num_end_at_zero = np.sum(walks[-1] == 0)
print(num_end_at_zero)
# Output: Count of walks ending at 0
# 13. Simulate a 2D random walk with step sizes drawn from a normal
distribution
x_steps = np.random.normal(0, 1, 500)
y_steps = np.random.normal(0, 1, 500)
x_position = np.cumsum(x_steps)
y_position = np.cumsum(y_steps)
print(x_position, y_position)
# Output: X and Y positions
# 14. Calculate the average final position of 1000 random walks
final_positions = np.cumsum(np.random.choice([-1, 1], size=(1000, 1000)),
axis=0)[-1]
avg_final_position = np.mean(final_positions)
print(avg_final_position)
# Output: Average final position
# 15. Count how many times a 1D walk reaches exactly position 5
count_at_five = np.sum(position == 5)
print(count_at_five)
# Output: Number of times the position is exactly 5
# 16. Simulate a constrained 1D random walk that cannot go below 0
position = np.zeros(1000)
for i in range(1, 1000):
step = np.random.choice([-1, 1])
position[i] = max(0, position[i-1] + step)
print(position)
# Output: Constrained walk positions
# 17. Simulate a 1D walk where the probability of moving up increases with
position
steps = np.random.rand(1000)
biased_steps = np.where(steps > (position / 1000), 1, -1)
position = np.cumsum(biased_steps)
print(position)
# Output: Biased walk positions
# 18. Simulate a 2D random walk with diagonal steps allowed
directions = np.array([[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, -1], [-1, 1], [1, -1]])
steps = directions[np.random.randint(0, 8, 500)]
position = np.cumsum(steps, axis=0)
print(position)
# Output: 2D positions
# 19. Compute the probability of a 1D random walk crossing 10 after 1000
simulations
crossings = 0
for _ in range(1000):
walk = np.cumsum(np.random.choice([-1, 1], size=1000))
if np.any(walk >= 10):
crossings += 1
probability = crossings / 1000
print(probability)
# Output: Probability of crossing 10
# 20. Simulate multiple 1D random walks at once and compute the mean and
std deviation of final positions
walks = np.cumsum(np.random.choice([-1, 1], size=(500, 1000)), axis=0)
final_positions = walks[-1]
mean_final = np.mean(final_positions)
std_final = np.std(final_positions)
print(f"Mean: {mean_final}, Std Dev: {std_final}")
# Output: Mean and std deviation of final positions
import numpy as np
# 1. Simulate 1000 random walks of 500 steps each
num_walks = 1000
num_steps = 500
walks = np.cumsum(np.random.choice([-1, 1], size=(num_steps, num_walks)),
axis=0)
print(walks)
# Output: 500x1000 matrix representing random walks
# 2. Find the final positions of all 1000 walks
final_positions = walks[-1]
print(final_positions)
# Output: Array of final positions
# 3. Compute the percentage of walks that end at exactly 0
percentage_zero = np.mean(final_positions == 0) * 100
print(f"{percentage_zero:.2f}%")
# Output: Percentage of walks ending at 0
# 4. Find the farthest distance from the origin reached in each walk
max_distances = np.max(np.abs(walks), axis=0)
print(max_distances)
# Output: Array of max distances for each walk
# 5. Find how many walks crossed position 10 at any point
crossed_10 = np.any(walks >= 10, axis=0)
num_crossed_10 = np.sum(crossed_10)
print(num_crossed_10)
# Output: Number of walks that crossed 10
# 6. Find the first time each walk reaches position 5
first_crossing_5 = np.argmax(walks >= 5, axis=0)
first_crossing_5[np.all(walks < 5, axis=0)] = -1 # Set -1 if never reached
print(first_crossing_5)
# Output: Indices of first crossing of 5 for each walk
# 7. Compute the mean final position of all walks
mean_final = np.mean(final_positions)
print(mean_final)
# Output: Mean of final positions
# 8. Compute the standard deviation of final positions
std_final = np.std(final_positions)
print(std_final)
# Output: Standard deviation of final positions
# 9. Simulate 1000 biased random walks (70% chance of +1, 30% chance of -1)
biased_walks = np.cumsum(np.random.choice([-1, 1], size=(num_steps,
num_walks), p=[0.3, 0.7]), axis=0)
print(biased_walks)
# Output: 500x1000 biased walks
# 10. Compute the mean final position for biased walks
mean_biased_final = np.mean(biased_walks[-1])
print(mean_biased_final)
# Output: Mean of final positions for biased walks
# 11. Find how many walks never go below zero
never_below_zero = np.all(walks >= 0, axis=0)
num_never_below_zero = np.sum(never_below_zero)
print(num_never_below_zero)
# Output: Number of walks that never dropped below zero
# 12. Compute the probability of reaching 15 at any point
prob_reach_15 = np.mean(np.any(walks >= 15, axis=0))
print(prob_reach_15)
# Output: Probability of reaching 15
# 13. Find the median final position of the walks
median_final = np.median(final_positions)
print(median_final)
# Output: Median final position
# 14. Compute the probability of ending above 20
prob_above_20 = np.mean(final_positions > 20)
print(prob_above_20)
# Output: Probability of ending above 20
# 15. Find the number of walks that cross zero at least once
crossed_zero = np.any(walks == 0, axis=0)
num_crossed_zero = np.sum(crossed_zero)
print(num_crossed_zero)
# Output: Number of walks that crossed zero
# 16. Find the longest streak of positive positions in each walk
def longest_positive_streak(walk):
pos_streaks = np.split(walk, np.where(walk <= 0)[0])
return max((len(streak) for streak in pos_streaks), default=0)
longest_streaks = np.apply_along_axis(longest_positive_streak, axis=0,
arr=walks)
print(longest_streaks)
# Output: Longest positive streak for each walk
# 17. Simulate 2D random walks (1000 walks, 500 steps each)
x_steps = np.random.choice([-1, 1], size=(num_steps, num_walks))
y_steps = np.random.choice([-1, 1], size=(num_steps, num_walks))
x_positions = np.cumsum(x_steps, axis=0)
y_positions = np.cumsum(y_steps, axis=0)
print(x_positions, y_positions)
# Output: 500x1000 matrices of x and y positions
# 18. Compute the final Euclidean distance from the origin for each 2D walk
final_distances = np.sqrt(x_positions[-1]**2 + y_positions[-1]**2)
print(final_distances)
# Output: Array of final distances
# 19. Compute the average final distance from the origin for 2D walks
mean_final_distance = np.mean(final_distances)
print(mean_final_distance)
# Output: Mean of final distances
# 20. Find the probability that a 2D walk reaches (10,10) at any step
reached_10_10 = np.any((x_positions == 10) & (y_positions == 10), axis=0)
prob_reach_10_10 = np.mean(reached_10_10)
print(prob_reach_10_10)
# Output: Probability of reaching (10,10)