Sarah111-AHM / Semsmah

2 stars 0 forks source link

Revision Exercises #11

Open Sarah111-AHM opened 1 year ago

Sarah111-AHM commented 1 year ago
  1. Create a 3x3 NumPy array with random values between 0 and 1. Then, calculate the mean and the median for each row then for each column and print the result then print the value of the standard deviation.

import numpy as np

Create a 3x3 NumPy array with random values

arr = np.random.rand(3, 3)

Calculate the mean and median for each row

row_means = np.mean(arr, axis=1) row_medians = np.median(arr, axis=1)

Calculate the mean and median for each column

col_means = np.mean(arr, axis=0) col_medians = np.median(arr, axis=0)

Calculate the standard deviation of the array

std_dev = np.std(arr)

Print the results

print("Array:") print(arr) print("Row means:", row_means) print("Row medians:", row_medians) print("Column means:", col_means) print("Column medians:", col_medians) print("Standard deviation:", std_dev)

Output:

Array: [[0.2101224 0.32041263 0.17109307] [0.954059 0.33772729 0.20424406] [0.98072563 0.7435479 0.55891915]] Row means: [0.2335427 0.49834345 0.76139789] Row medians: [0.2101224 0.33772729 0.7435479 ] Column means: [0.71530234 0.46722994 0.31108543] Column medians: [0.954059 0.33772729 0.20424406] Standard deviation: 0.3212908368257777

2. Create a NumPy array with the values [1, 2, 3, 4, 5]. Using slicing, extract the values at the even indices and print the result.

Here is the code to create a NumPy array with the values [1, 2, 3, 4, 5] and extract the values at the even indices using slicing:

import numpy as np

# Create a NumPy array with the values [1, 2, 3, 4, 5]
arr = np.array([1, 2, 3, 4, 5])

# Extract the values at the even indices using slicing
even_indices = arr[::2]

# Print the result
print(even_indices)

Output:

[1 3 5]

3. Create a 4x4 NumPy array with the values [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]. Using slicing, extract the subarray with the values [[6, 7], [10, 11]] and print the result.
4. Create a NumPy array with values ranging from 0 to 9 and extract the even values in a new array and the primary numbers in a new array.
5. Create a NumPy array with values ranging from 0 to 9 and reshape it to a 3x3 array. Then, slice the array to obtain a 2x2 array starting from the second row and second column.
6. Create a NumPy array with values ranging from 0 to 9 and use Boolean indexing to replace all odd values with -1.
7. Create a NumPy array with values ranging from 0 to 9 and use fancy indexing to obtain a new array with the elements in reverse order.