<jupyter_start><jupyter_text>Q 1.Write a NumPy program to get the numpy version and show numpy build configuration.<jupyter_code>import numpy as np
print(np.__version__)
print(np.show_config())<jupyter_output>1.18.5
blas_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/ersar/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\lib', 'C:/Users/ersar/anaconda3\\Library\\include']
blas_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/Users/ersar/anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2019.0.117\\windows\\mkl\[...]<jupyter_text>Q2. Write a NumPy program to  get help on the add function.<jupyter_code>import numpy as np
print(np.info(np.add))<jupyter_output>add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or None,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``,[...]<jupyter_text>Q3. Write a NumPy program to test whether none of the elements of a given array is zero.<jupyter_code>import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))<jupyter_output>Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False<jupyter_text>Q4. Write a NumPy program to test whether any of the elements of a given array is non-zero.<jupyter_code>import numpy as np
x = np.array([1, 0, 0, 0])
print("Original array:")
print(x)
print("Test whether any of the elements of a given array is non-zero:")
print(np.any(x))
x = np.array([0, 0, 0, 0])
print("Original array:")
print(x)
print("Test whether any of the elements of a given array is non-zero:")
print(np.any(x))<jupyter_output>Original array:
[1 0 0 0]
Test whether any of the elements of a given array is non-zero:
True
Original array:
[0 0 0 0]
Test whether any of the elements of a given array is non-zero:
False<jupyter_text>Q5. Write a NumPy program to test a given array element-wise for finiteness (not infinity or not a Number).<jupyter_code>import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print("Original array")
print(a)
print("Test a given array element-wise for finiteness :")
print(np.isfinite(a))<jupyter_output>Original array
[ 1.  0. nan inf]
Test a given array element-wise for finiteness :
[ True  True False False]<jupyter_text>Q6. Write a NumPy program to test element-wise for positive or negative infinity.<jupyter_code>import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print("Original array")
print(a)
print("Test element-wise for positive or negative infinity:")
print(np.isinf(a))<jupyter_output>Original array
[ 1.  0. nan inf]
Test element-wise for positive or negative infinity:
[False False False  True]<jupyter_text>Q7. Write a NumPy program to test element-wise for NaN of a given array.<jupyter_code>import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print("Original array")
print(a)
print("Test element-wise for NaN:")
print(np.isnan(a))<jupyter_output>Original array
[ 1.  0. nan inf]
Test element-wise for NaN:
[False False  True False]<jupyter_text>Q8. Write a NumPy program to test element-wise for complex number, real number of a given array. Also test whether a given number is a scalar type or not.<jupyter_code>import numpy as np
a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j])
print("Original array")
print(a)
print("Checking for complex number:")
print(np.iscomplex(a))
print("Checking for real number:")
print(np.isreal(a))
print("Checking for scalar type:")
print(np.isscalar(3.1))
print(np.isscalar([3.1]))<jupyter_output>Original array
[1. +1.j 1. +0.j 4.5+0.j 3. +0.j 2. +0.j 0. +2.j]
Checking for complex number:
[ True False False False False  True]
Checking for real number:
[False  True  True  True  True False]
Checking for scalar type:
True
False<jupyter_text>Q9. Write a NumPy program to test whether two arrays are element-wise equal within a tolerance.<jupyter_code>import numpy as np
print("Test if two arrays are element-wise equal within a tolerance:")
print(np.allclose([1e10,1e-7], [1.00001e10,1e-8]))
print(np.allclose([1e10,1e-8], [1.00001e10,1e-9]))
print(np.allclose([1e10,1e-8], [1.0001e10,1e-9]))
print(np.allclose([1.0, np.nan], [1.0, np.nan]))
print(np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True))<jupyter_output>Test if two arrays are element-wise equal within a tolerance:
False
True
False
False
True<jupyter_text>Q10. Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays.<jupyter_code>import numpy as np
x = np.array([3, 5])
y = np.array([2, 5])
print("Original numbers:")
print(x)
print(y)
print("Comparison - greater")
print(np.greater(x, y))
print("Comparison - greater_equal")
print(np.greater_equal(x, y))
print("Comparison - less")
print(np.less(x, y))
print("Comparison - less_equal")
print(np.less_equal(x, y))<jupyter_output>Original numbers:
[3 5]
[2 5]
Comparison - greater
[ True False]
Comparison - greater_equal
[ True  True]
Comparison - less
[False False]
Comparison - less_equal
[False  True]<jupyter_text>Q11. Write a NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays.<jupyter_code>import numpy as np
x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100])
y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001])
print("Original numbers:")
print(x)
print(y)
print("Comparison - equal:")
print(np.equal(x, y))
print("Comparison - equal within a tolerance:")
print(np.allclose(x, y))<jupyter_output>Original numbers:
[  72   79   85   90  150 -135  120  -10   60  100]
[  72.         79.         85.         90.        150.       -135.
  120.        -10.         60.        100.000001]
Comparison - equal:
[ True  True  True  True  True  True  True  True  True False]
Comparison - equal within a tolerance:
True<jupyter_text>Q12. Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array.<jupyter_code>import numpy as np
X = np.array([1, 7, 13, 105])
print("Original array:")
print(X)
print("Size of the memory occupied by the said array:")
print("%d bytes" % (X.size * X.itemsize))<jupyter_output>Original array:
[  1   7  13 105]
Size of the memory occupied by the said array:
16 bytes<jupyter_text>Q13. Write a NumPy program to create an array of 10 zeros,10 ones, 10 fives.<jupyter_code>import numpy as np
array=np.zeros(10)
print("An array of 10 zeros:")
print(array)
array=np.ones(10)
print("An array of 10 ones:")
print(array)
array=np.ones(10)*5
print("An array of 10 fives:")
print(array)<jupyter_output>An array of 10 zeros:
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
An array of 10 ones:
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
An array of 10 fives:
[5. 5. 5. 5. 5. 5. 5. 5. 5. 5.]<jupyter_text>Q14. Write a NumPy program to create an array of the integers from 30 to70.<jupyter_code>import numpy as np
array=np.arange(30,71)
print("Array of the integers from 30 to70")
print(array)<jupyter_output>Array of the integers from 30 to70
[30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70]<jupyter_text>Q15. Write a NumPy program to create an array of all the even integers from 30 to 70.<jupyter_code>import numpy as np
array=np.arange(30,71,2)
print("Array of all the even integers from 30 to 70")
print(array)<jupyter_output>Array of all the even integers from 30 to 70
[30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70]<jupyter_text>Q16. Write a NumPy program to create a 3x3 identity matrix.<jupyter_code>import numpy as np
array_2D=np.identity(3)
print('3x3 matrix:')
print(array_2D)<jupyter_output>3x3 matrix:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]<jupyter_text>Q17. Write a NumPy program to generate a random number between 0 and 1.<jupyter_code>import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1:")
print(rand_num)<jupyter_output>Random number between 0 and 1:
[-2.12383725]<jupyter_text>Q18. Write a NumPy program to generate an array of 15 random numbers from a standard normal distribution.<jupyter_code>import numpy as np
rand_num = np.random.normal(0,1,15)
print("15 random numbers from a standard normal distribution:")
print(rand_num)<jupyter_output>15 random numbers from a standard normal distribution:
[ 0.9650088   0.58380321  1.02234596 -1.50403544  0.15303111  0.18649727
  0.08983726 -1.40424735  0.20575861  1.45706169 -1.50342413 -0.73298994
 -0.50336726 -0.2301621   0.38561666]<jupyter_text>Q19. Write a NumPy program to create a vector with values ranging from 15 to 55 and print all values except the first and last.<jupyter_code>import numpy as np
v = np.arange(15,55)
print("Original vector:")
print(v)
print("All values except the first and last of the said vector:")
print(v[1:-1])<jupyter_output>Original vector:
[15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54]
All values except the first and last of the said vector:
[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 40 41 42 43 44 45 46 47 48 49 50 51 52 53]<jupyter_text>Q20. Write a NumPy program to create a 3X4 array using and iterate over it.<jupyter_code>import numpy as np
a = np.arange(10,22).reshape((3, 4))
print("Original array:")
print(a)
print("Each element of the array is:")
for x in np.nditer(a):
  print(x,end=" ")<jupyter_output>Original array:
[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]
Each element of the array is:
10 11 12 13 14 15 16 17 18 19 20 21<jupyter_text>Q21. Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50.<jupyter_code>import numpy as np
v = np.linspace(10, 49, 5)
print("Length 10 with values evenly distributed between 5 and 50:")
print(v)<jupyter_output>Length 10 with values evenly distributed between 5 and 50:
[10.   19.75 29.5  39.25 49.  ]<jupyter_text>Q22. Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15.<jupyter_code>import numpy as np
x = np.arange(21)
print("Original vector:")
print(x)
print("After changing the sign of the numbers in the range from 9 to 15:")
x[(x >= 9) & (x <= 15)] *= -1
print(x)<jupyter_output>Original vector:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]
After changing the sign of the numbers in the range from 9 to 15:
[  0   1   2   3   4   5   6   7   8  -9 -10 -11 -12 -13 -14 -15  16  17
  18  19  20]<jupyter_text>Q23. Write a NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10.<jupyter_code>import numpy as np
x = np.random.randint(0, 11, 5)
print("Vector of length 5 filled with arbitrary integers from 0 to 10:")
print(x)<jupyter_output>Vector of length 5 filled with arbitrary integers from 0 to 10:
[1 2 4 2 7]<jupyter_text>Q24. Write a NumPy program to multiply the values of two given vectors.<jupyter_code>import numpy as np
x = np.array([1, 8, 3, 5])
print("Vector-1")
print(x)
y= np.random.randint(0, 11, 4)
print("Vector-2")
print(y)
result = x * y
print("Multiply the values of two said vectors:")
print(result)<jupyter_output>Vector-1
[1 8 3 5]
Vector-2
[ 5  3 10  8]
Multiply the values of two said vectors:
[ 5 24 30 40]<jupyter_text>Q25. Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21.<jupyter_code>import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(m)<jupyter_output>[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]<jupyter_text>Q26. Write a NumPy program to find the number of rows and columns of a given matrix.<jupyter_code>import numpy as np
m= np.arange(10,22).reshape((3, 4))
print("Original matrix:")
print(m)
print("Number of rows and columns of the said matrix:")
print(m.shape)<jupyter_output>Original matrix:
[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]
Number of rows and columns of the said matrix:
(3, 4)<jupyter_text>Q27. Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0.<jupyter_code>import numpy as np
x = np.eye(3)
print(x)<jupyter_output>[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]<jupyter_text>Q28. Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.<jupyter_code>import numpy as np
x = np.ones((10, 10))
x[1:-1, 1:-1] = 0
print(x)<jupyter_output>[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]<jupyter_text>Q29. Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.<jupyter_code>import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)<jupyter_output>[[1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]
 [0 0 0 0 5]]<jupyter_text>Q30. Write a NumPy program to create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.<jupyter_code>import numpy as np
x = np.zeros((4, 4))
x[::2, 1::2] = 1
x[1::2, ::2] = 1
print(x)<jupyter_output>[[0. 1. 0. 1.]
 [1. 0. 1. 0.]
 [0. 1. 0. 1.]
 [1. 0. 1. 0.]]<jupyter_text>Q31. Write a NumPy program to create a 3x3x3 array filled with arbitrary values.<jupyter_code>import numpy as np
x = np.random.random((3, 3, 3))
print(x)<jupyter_output>[[[0.87169043 0.16845734 0.86545461]
  [0.71147845 0.25207571 0.12543201]
  [0.90138652 0.55375416 0.05953588]]

 [[0.30443163 0.32260459 0.64969417]
  [0.88021015 0.75464034 0.04331251]
  [0.21070551 0.91985838 0.82608406]]

 [[0.61044164 0.60470635 0.80709703]
  [0.44013109 0.44076098 0.84672559]
  [0.64298421 0.01622318 0.37075796]]]<jupyter_text>Q32. Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array.<jupyter_code>import numpy as np
x = np.array([[0,1],[2,3]])
print("Original array:")
print(x)
print("Sum of all elements:")
print(np.sum(x))
print("Sum of each column:")
print(np.sum(x, axis=0))
print("Sum of each row:")
print(np.sum(x, axis=1))<jupyter_output>Original array:
[[0 1]
 [2 3]]
Sum of all elements:
6
Sum of each column:
[2 4]
Sum of each row:
[1 5]<jupyter_text>Q33. Write a NumPy program to compute the inner product of two given vectors.<jupyter_code>import numpy as np
x = np.array([4, 5])
y = np.array([7, 10])
print("Original vectors:")
print(x)
print(y)
print("Inner product of said vectors:")
print(np.dot(x, y))<jupyter_output>Original vectors:
[4 5]
[ 7 10]
Inner product of said vectors:
78<jupyter_text>Q34. Write a NumPy program to add a vector to each row of a given matrix.<jupyter_code>import numpy as np
m = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 1, 0])
print("Original vector:")
print(v)
print("Original matrix:")
print(m)
result = np.empty_like(m) 
for i in range(4):
  result[i, :] = m[i, :] + v
print("\nAfter adding the vector v to each row of the matrix m:")
print(result)<jupyter_output>Original vector:
[1 1 0]
Original matrix:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

After adding the vector v to each row of the matrix m:
[[ 2  3  3]
 [ 5  6  6]
 [ 8  9  9]
 [11 12 12]]<jupyter_text>Q35. Write a NumPy program to save a given array to a binary file .<jupyter_code>import numpy as np
import os
a = np.arange(20)
np.save('temp_arra.npy', a)
print("Check if 'temp_arra.npy' exists or not?")
if os.path.exists('temp_arra.npy'):
    x2 = np.load('temp_arra.npy')
    print(np.array_equal(a, x2))<jupyter_output>Check if 'temp_arra.npy' exists or not?
True<jupyter_text>Q36. Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it.<jupyter_code>import numpy as np
import os
x = np.arange(10)
y = np.arange(11, 20)
print("Original arrays:")
print(x)
print(y)
np.savez('temp_arra.npz', x=x, y=y)
print("Load arrays from the 'temp_arra.npz' file:")
with np.load('temp_arra.npz') as data:
    x2 = data['x']
    y2 = data['y']
    print(x2)
    print(y2)<jupyter_output>Original arrays:
[0 1 2 3 4 5 6 7 8 9]
[11 12 13 14 15 16 17 18 19]
Load arrays from the 'temp_arra.npz' file:
[0 1 2 3 4 5 6 7 8 9]
[11 12 13 14 15 16 17 18 19]<jupyter_text>Q37. Write a NumPy program to save a given array to a text file and load it.<jupyter_code>import numpy as np
import os
x = np.arange(12).reshape(4, 3)
print("Original array:")
print(x)
header = 'col1 col2 col3'
np.savetxt('temp.txt', x, fmt="%d", header=header) 
print("After loading, content of the text file:")
result = np.loadtxt('temp.txt')
print(result)<jupyter_output>Original array:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
After loading, content of the text file:
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]]<jupyter_text>Q38. Write a NumPy program to convert a given array into bytes, and load it as array.<jupyter_code>import numpy as np
import os
a = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(a)
a_bytes = a.tostring()
a2 = np.fromstring(a_bytes, dtype=a.dtype)
print("After loading, content of the text file:")
print(a2)
print(np.array_equal(a, a2))<jupyter_output>Original array:
[1 2 3 4 5 6]
After loading, content of the text file:
[1 2 3 4 5 6]
True<jupyter_text>Q39. Write a NumPy program to convert a given array into a list and then convert it into a list again.<jupyter_code>import numpy as np
a = [[1, 2], [3, 4]]
x = np.array(a)
a2 = x.tolist()
print(a == a2)<jupyter_output>True<jupyter_text>Q40. Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.2)
y = np.sin(x)
print("Plot the points using matplotlib:")
plt.plot(x, y)
plt.show()<jupyter_output>Plot the points using matplotlib:<jupyter_text>Q41. Write a NumPy program to convert numpy dtypes to native python types.<jupyter_code>import numpy as np
print("numpy.float32 to python float")
x = np.float32(0)
print(type(x))
pyval = x.item()
print(type(pyval))<jupyter_output>numpy.float32 to python float
<class 'numpy.float32'>
<class 'float'>
{'fraction_non_alphanumeric': 0.1284788029925187, 'fraction_numerical': 0.09591022443890275, 'mean_word_length': 4.0839249492900604, 'pattern_counts': {'":': 0, '<': 127, '<?xml version=': 0, '>': 127, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '41', 'dir': 'jupyter-structured-clean-dedup', 'id': '530845', 'license': 'MIT', 'n_tokens_mistral': 8866, 'n_tokens_neox': 7411, 'n_words': 2788, 'path': 'NumPy/NumPy Basic.ipynb', 'repo_name': 'sarojkrjha/PythonWorkSheet', 'size': '20050'}