Python & NumPy 1) (5pts) Using NumPy data structures, multiply the following two
ID: 3804385 • Letter: P
Question
Python & NumPy
1) (5pts) Using NumPy data structures, multiply the following two vectors element-by-element. Print out the vectors and the result neatly.
Vector A: [28.35, -98.78, 22.19, 45.71, 67.12, 48.38, -12.34]
Vector B: [35.28, -78.98, 19.22, 71.45, 12.67, 38.48, -34.12]
2) (10pts) Use built-in NumPy functions to generate the following vectors and matrices. Print each one out:
X = a 4x4 matrix of all zeroes.
Y = a vector of all ones, the same shape as Vector A from Problem 1 above (use a NumPy function, do not hardcode values).
Z = an identity matrix of size 8 (8x8).
3) (15pts) Create the following NumPy array:
c1 = an array of 5 unsigned 8-bit integers. Print it out, also print out its dtype on the same line. Then via print statements in your code, answer the following questions:
Can you store the value -7 in this array? Why or why not?
Can you store the value 58 in this array? Why or why not?
Can you store the value 1002 in this array? Why or why not?
Use a loop to add 1000 to the values in your array 100 times. Print out the array and its dtype. What has occurred? Is this what you expected to see?
4) (10pts) Use NumPy's astype function to make the following copies. Print out the vectors and their dtypes:
Create a copy of the array from Problem 3, keeping its dtype the same.
Create a copy of the array from Problem 3, changing its dtype to 64-bit floating point.
5) (10pts) Create an NumPy array and a print statement that will produce the following output when your code runs:
array: ['1' '2'] and its dtype is: |S1
What type is "s1"? (answer via a print statement in your code).
Try convert this array to an array of integers using NumPy's astype functions (print out results). Does it work? How can this be useful in data processing? What challenges might you anticipate to encounter when converting text data to numerical data? (answer via prints).
Explanation / Answer
I solved first two questions:
code:
import os
import sys
import numpy as np
#second question
def gen_vector_mat():
mat1 = np.zeros((4, 4))
print mat1
vec = np.ones((1,7))
print vec
mat3 = np.ones((8,8))
print mat3
#for 1st question
a = np.array([28.35, -98.78, 22.19, 45.71, 67.12, 48.38, -12.34])
b= np.array([35.28, -78.98, 19.22, 71.45, 12.67, 38.48, -34.12])
print a*b
#first question end
gen_vector_mat()
output:
[ 1000.188 7801.6444 426.4918 3265.9795 850.4104 1861.6624
421.0408]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 1. 1. 1. 1. 1. 1. 1.]]
[[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1.]]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.