Professional Documents
Culture Documents
1. You have an array of shape (5, 5). Using NumPy, create a new array that contains the
diagonal elements of the original array.
[23]: import numpy as np
diagonal_arr = np.diagonal(arr)
Original array:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]
Diagonal array:
[ 1 7 13 19 25]
2. You have two arrays of shape (3, 3) and (3, 1). Using NumPy, perform matrix multiplication
of these arrays.
[2]: import numpy as np
# matrix multiplication
result = np.dot(array1, array2)
1
print(result)
[[14]
[32]
[50]]
3. You are given an array of integers. Using NumPy, create a new array that contains only the
unique elements of the original array.
[16]: import numpy as np
print(B)
[1 2 3 4 5 6]
4. You have two arrays of shape (3, 3) and (3, 4). Using NumPy, concatenate these arrays along
the first axis.
[17]: import numpy as np
print(D)
[[ 1 2 3 10 11 12 13]
[ 4 5 6 14 15 16 17]
[ 7 8 9 18 19 20 21]]
6. You have an array of shape (4, 4). Using NumPy, split it into two equal parts horizontally.
2
# split the array horizontally into two parts
arr1, arr2 = np.split(arr, 2, axis=1)
[[ 1 2]
[ 5 6]
[ 9 10]
[13 14]]
[[ 3 4]
[ 7 8]
[11 12]
[15 16]]
10. You have a data frame containing the names, ages and salaries of employees. Using Pandas,
create a new data frame that contains only the names and salaries of employees who are older
than 30 years.
[1]: import pandas as pd
# create a new data frame with only names and salaries of employees who are␣
↪older than 30 years
print(new_df)
Name Salary
1 Bob 70000
2 Charlie 90000
11. You have two data frames containing the names, ages and genders of students from two
different classes. Using Pandas, merge these data frames on the basis of the names of the
students and add a new column that contains the average age of the students from both
classes.
[14]: import pandas as pd
3
# create the second data frame
class2 = pd.DataFrame({'Name': ['HARIKA', 'RAM', 'SITHA', 'ABHI'],
'Age': [30, 27, 38, 33],
'Gender': ['Female', 'Male', 'Female', 'Male']})
4
if min_marks <= marks <= max_marks:
return grade
df['Grade'] = df['Marks'].apply(get_grade)
print(grouped_df)
Marks
mean median std
Grade
A 91.500000 91.5 0.707107
B 83.000000 83.0 1.414214
C 73.333333 74.0 2.081666
D 62.000000 62.0 1.414214
[ ]: