DAV
DAV
# 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
# 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)
# 7. Precision difference
b6 = np.float16(0.1)
b7 = np.float64(0.1)
print(b6, b7)
# 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.]
# 9. Logarithm of zero
m = np.log(np.array([0, 1, 10]))
print(m) # Output: [-inf 0. 2.30258509]
import numpy as np
# 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]]
# 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]]
import numpy as np
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)
# 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
# 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]
# 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
import numpy as np
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
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
# 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]
# 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]
import numpy as np
import numpy as np
# 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]
import numpy as np
# 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]]
# 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)
import numpy as np
import numpy as np
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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)
# 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)