Python Numpyquestions
Python Numpyquestions
Ans:- NumPy is used to work with arrays. The array object in NumPy is called ndarray.
Example :-
import numpy as np
print(arr)
print(type(arr))
A dimension in arrays is one level of array depth (nested arrays). nested array: are
arrays that have arrays as their elements.
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These
are the most common and basic arrays.
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array. These are often used to
represent matrix or 2nd order tensors.
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are
often used to represent a 3rd order tensor.
Example :- arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
Ans:-
import numpy as np
print("Matrix a : \n", a)
print("\nMatrix b : \n", b)
Ans:-
arr.sort()
print(arr)
if __name__ == "__main__":
arr = [4, 3, 7, 8, 6, 2, 1]
n = len(arr)
zigZag(arr, n)
Ans:-
In python sequence data types, we can access elements by indexing and slicing.
Sequence data types are strings, list, tuple, range objects.
Indexing: Indexing is used to obtain individual elements. Indexing starts from 0. Index 0
represents the first element in the sequence.
Negative indexing starts from -1. Index -1 represents the last element in the sequence.
Slicing: Slicing is used to obtain a sequence of elements. In slicing, we specify the start
index and end index.
Indexing and Slicing can be be done in Python Sequences types like list, string, tuple,
range objects.
# importing package
import numpy
[3, 4, 6, 5],
[6, 5, 6, 5],
[6, 5, 7, 8]])
# Counting sequence
# view output
print(output)
import numpy as np
print(n_array)
trace = np.trace(n_array)
print("\nTrace of given 3X3 matrix:")
print(trace)
Ans:-
import numpy as np
dimension = 4
print(identity_matrix)
8. Develop a program to generate 200 random numbers between 1 and 1000 by using
numpy.
Ans:-
import random
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
num = 200
start = 1
end = 1000
print(Rand(start, end, num))
9. Create a NumPy 2-D array named "MyArray" having 2 rows and 5 columns and the
elements are set to 1 - 10 and data-type set as int.
Ans:--
import numpy as np
MyArray=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype='i')
print(MyArray)
print(type(MyArray))
10. Create a NumPy array named "zeros" having 10 elements and all the elements are
set to zero.
Ans:-
import numpy as np
zeros=np.zeros(10)
print(zeros)
print(type(zeros))