0% found this document useful (0 votes)
78 views54 pages

3.2 Numpy Array Sample Programs

The document provides a comprehensive overview of using NumPy in Python, including examples of creating arrays from lists and tuples, performing basic operations, and executing advanced tasks like reshaping and indexing. It also covers exercises to reinforce understanding of NumPy functionalities such as finding unique elements, common values, and performing array operations. The content is structured with code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

Rajesh B.M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views54 pages

3.2 Numpy Array Sample Programs

The document provides a comprehensive overview of using NumPy in Python, including examples of creating arrays from lists and tuples, performing basic operations, and executing advanced tasks like reshaping and indexing. It also covers exercises to reinforce understanding of NumPy functionalities such as finding unique elements, common values, and performing array operations. The content is structured with code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

Rajesh B.M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Example 1: numpy.

array()

1. import numpy as np
2. arr=np.array([1,2,3])
3. arr

Output:

array([1, 2, 3])

In the above code

o We have imported numpy with alias name np.


o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
o In the array() function, we have passed only the elements, not axis.
o Lastly, we have tried to print the value of arr.

In the output, an array has been shown.

Example 2:

1. import numpy as np
2. arr=np.array([1.,2.,3.])
3. arr

Output:

array([1., 2., 3.])

In the above code

o We have imported numpy with alias name np.


o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
o In the array() function, we have passed elements of different type such
as integer, float, etc.
o Lastly, we have tried to print the value of arr.
In the output, an array has been displayed containing elements in such type
which require minimum memory to hold the object in the sequence.

Example 3: More than one dimensions

1. import numpy as np
2. arr=np.array([[1,2.,3.],[4.,5.,7]])
3. arr

Output:

array([[1., 2., 3.],


[4., 5., 7.]])

In the above code

o We have imported numpy with alias name np.


o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
o In the array() function, we have passed the number of elements in
different square brackets.
o Lastly, we have tried to print the value of arr.

In the output, a multi-dimensional array has been shown.

Example 4: Minimum dimensions: 2

1. import numpy as np
2. arr=np.array([1,2.,3.],ndmin=2)
3. arr

Output:

array([[1., 2., 3.]])

In the above code

o We have imported numpy with alias name np.


o We have declared the 'arr' variable and assigned the value returned by
np.array() function.
o In the array() function, we have passed the number of elements in a
square bracket and the dimension to create a ndarray.
o Lastly, we have tried to print the value of arr.

In the output, a two-dimensional array has been shown.

Example 5: Type provided

1. import numpy as np
2. arr=np.array([12,45.,3.],dtype=complex)
3. arr

Output:

array([12.+0.j, 45.+0.j, 3.+0.j])

In the above code

o We have imported numpy with alias name np.


o We have declared the 'arr' variable and assigned the value returned by
the np.array() function.
o In the array() function, we have passed the elements in the square
bracket and set the dtype to complex.
o Lastly, we have tried to print the value of arr.

In the output, the values of the 'arr' elements have been shown in the form
of complex numbers.

Create NumPy Array from a List

You can use the np alias to create ndarray of a list using the array() method.
li = [1,2,3,4]
numpyArr = np.array(li)
or
numpyArr = np.array([1,2,3,4])
The list is passed to the array() method which then returns a NumPy array with
the same elements.
Example 1: The following example shows how to initialize a NumPy array from
a list.
 Python3

import numpy as np

li = [1, 2, 3, 4]

numpyArr = np.array(li)

print(numpyArr)

Output:
[1 2 3 4]
The resulting array looks the same as a list but is actually a NumPy object.
Example 2: Let’s take an example to check whether the numpyArr is a NumPy
object or not. In this example, we are using array() function to convert the list
into NumPy array then checking if it’s an NumPy object or not.
 Python3

import numpy as np

li = [1, 2, 3, 4]

numpyArr = np.array(li)

print("li =", li, "and type(li) =", type(li))

print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr))

Output:
li = [1, 2, 3, 4] and type(li) = <class 'list'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class
'numpy.ndarray'>
As you can see li is a list object whereas numpyArr is an array object of NumPy.

Create NumPy Array from a Tuple


You can make ndarray from a tuple using similar syntax.
tup = (1,2,3,4)
numpyArr = np.array(tup)
or
numpyArr = np.array((1,2,3,4))
The following example illustrates how to create a NumPy array from a tuple.
Here, we are using array() function to convert the tuple to NumPy array.
 Python3

import numpy as np

tup = (1, 2, 3, 4)

numpyArr = np.array(tup)

print("tup =", tup, "and type(tup) =", type(tup))

print("numpyArr =", numpyArr, "and type(numpyArr) =", type(numpyArr))

Output:
tup = (1, 2, 3, 4) and type(tup) = <class 'tuple'>
numpyArr = [1 2 3 4] and type(numpyArr) = <class
'numpy.ndarray'>
Note that the value of numpyArr remains the same for either of the two
conversions.
reating a NumPy Array:

LIST OF numpy array sample program in python


import numpy as np

arr = np.array([1, 2, 3, 4, 5])


Basic NumPy Operations:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print("Sum:", np.sum(arr))

print("Mean:", np.mean(arr))

print("Max:", np.max(arr))

print("Min:", np.min(arr))

Array Operations:

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

print("Element-wise addition:", arr1 + arr2)

print("Element-wise multiplication:", arr1 * arr2)

Reshaping a NumPy Array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

reshaped_arr = arr.reshape(2, 3)

print(reshaped_arr)

Indexing and Slicing:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


print("First element:", arr[0])

print("Slicing from index 1 to 3:", arr[1:4])

Boolean Indexing:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

mask = arr > 3

print("Elements greater than 3:", arr[mask])

Generating NumPy Arrays:

import numpy as np

zeros_array = np.zeros((2, 3))

ones_array = np.ones((3, 2))

random_array = np.random.rand(2, 2)

Array Concatenation:

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

concatenated = np.concatenate((arr1, arr2))

Array Transposition:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

transposed = arr.T

print(transposed)
Vector Dot Product:

import numpy as np

vector1 = np.array([1, 2, 3])

vector2 = np.array([4, 5, 6])

dot_product = np.dot(vector1, vector2)

print(dot_product)

These sample programs cover a range of common operations and tasks you might
perform with NumPy arrays in Python. You can use them as a starting point for
your own projects and data analysis tasks.

NumPy: Array Object Exercise-1 with Solution

Write a NumPy program to print the NumPy version on your system.

Sample Solution:-

Python Code:
import numpy as np

print(np.__version__)

Copy

Sample Output:
1.12.0
Explanation:

NumPy: Array Object Exercise-2 with Solution

Write a NumPy program to convert a list of numeric values into a one-


dimensional NumPy array.
Sample Solution:-

Python Code:
import numpy as np

l = [12.23, 13.32, 100, 36.32]

print("Original List:",l)

a = np.array(l)

print("One-dimensional NumPy array: ",a)

Copy

Sample Output:
Original List: [12.23, 13.32, 100, 36.32]
One-dimensional NumPy array: [ 12.23 13.32 100. 36.32]
NumPy: Array Object Exercise-3 with Solution

Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.

Sample Solution:-

Python Code:
import numpy as np

x = np.arange(2, 11).reshape(3,3)

print(x)

Copy

Sample Output:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]

NumPy: Array Object Exercise-4 with Solution

Write a NumPy program to create a null vector of size 10 and update the sixth
value to 11.

Sample Solution:-

Python Code:
import numpy as np

x = np.zeros(10)

print(x)

print("Update sixth value to 11")

x[6] = 11

print(x)

Sample Output:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Update sixth value to 11
[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]

NumPy: Array Object Exercise-5 with Solution

Write a NumPy program to create an array with values ranging from 12 to 38.

Sample Solution:-

Python Code:
import numpy as np

x = np.arange(12, 38)

print(x)

Copy

Sample Output:
[12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35
36
37]
numPy: Array Object Exercise-6 with Solution

Write a NumPy program to reverse an array (the first element becomes the last).

Sample Solution:-

Python Code:
import numpy as np

import numpy as np

x = np.arange(12, 38)

print("Original array:")

print(x)

print("Reverse array:")

x = x[::-1]

print(x)

Copy

Sample Output:
Original array:
[12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35
36
37]
Reverse array:
[37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17
16 15 14
13
12]

NumPy: Array Object Exercise-7 with Solution

Write a NumPy program to convert an array to a floating type.

Sample Solution:-

Python Code:
import numpy as np
import numpy as np

a = [1, 2, 3, 4]

print("Original array")

print(a)

x = np.asfarray(a)

print("Array converted to a float type:")

print(x)

Copy

Sample Output:
Original array
[1, 2, 3, 4]
Array converted to a float type:
[ 1. 2. 3. 4.]

NumPy: Array Object Exercise-8 with Solution

Write a NumPy program to create a 2D array with 1 on the border and 0 inside.
Sample Solution:-

Python Code:
import numpy as np

x = np.ones((5,5))

print("Original array:")

print(x)

print("1 on the border and 0 inside in the array")


x[1:-1,1:-1] = 0
print(x)

Copy

Sample Output:
Original array:
[[ 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 on the border and 0 inside in the array
[[ 1. 1. 1. 1. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
Write a NumPy program to test whether each element of a 1-D array is also
present in a second array.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np

array1 = np.array([0, 10, 20, 40, 60])


print("Array1: ",array1)

array2 = [0, 40]

print("Array2: ",array2)

print("Compare each element of array1 and array2")

print(np.in1d(array1, array2))

Copy
Sample Output:
Array1: [ 0 10 20 40 60]
Array2: [0, 40]
Compare each element of array1 and array2
[ True False False True False]

Write a NumPy program to find common values between two arrays.

Pictorial Presentation:

Sample Solution:-
Python Code:
import numpy as np

array1 = np.array([0, 10, 20, 40, 60])

print("Array1: ",array1)

array2 = [10, 30, 40]

print("Array2: ",array2)

print("Common values between two arrays:")

print(np.intersect1d(array1, array2))

Copy
Sample Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]
Write a NumPy program to get the unique elements of an array.

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np

x = np.array([10, 10, 20, 20, 30, 30])

print("Original array:")

print(x)

print("Unique elements of the above array:")

print(np.unique(x))

x = np.array([[1, 1], [2, 3]])

print("Original array:")

print(x)

print("Unique elements of the above array:")

print(np.unique(x))
Copy
Sample Output:
Original array:
[10 10 20 20 30 30]
Unique elements of the above array:
[10 20 30]
Original array:
[[1 1]
[2 3]]
Unique elements of the above array:
[1 2 3]
Write a NumPy program to find the union of two arrays. Union will return a
unique, sorted array of values in each of the two input arrays.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np

array1 = np.array([0, 10, 20, 40, 60, 80])

print("Array1: ",array1)

array2 = [10, 30, 40, 50, 70]

print("Array2: ",array2)

print("Unique sorted array of values that are in either of the


two input arrays:")

print(np.union1d(array1, array2))

Copy
Sample Output:
Array1: [ 0 10 20 40 60 80]
Array2: [10, 30, 40, 50, 70]
Unique sorted array of values that are in either of the two input
array
s:
[ 0 10 20 30 40 50 60 70 80]

Write a NumPy program to test if all elements in an array evaluate to True.


Note: 0 evaluates to False in python.

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np

print(np.all([[True,False],[True,True]]))

print(np.all([[True,True],[True,True]]))

print(np.all([10, 20, 0, -50]))

print(np.all([10, 20, -50]))

Copy
Sample Output:
False
True
False
True
Write a NumPy program to repeat array elements.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np

x = np.repeat(3, 4)

print(x)

x = np.array([[1,2],[3,4]])

print(np.repeat(x, 3))

Copy
Sample Output:
[3 3 3 3]
[1 1 2 2 3 3 4 4]

Write a NumPy program to compare two arrays using NumPy.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np

a = np.array([1, 2])

b = np.array([4, 5])

print("Array a: ",a)

print("Array b: ",b)

print("a > b")

print(np.greater(a, b))

print("a >= b")

print(np.greater_equal(a, b))

print("a < b")

print(np.less(a, b))

print("a <= b")

print(np.less_equal(a, b))

Copy
Sample Output:
Array a: [1 2]
Array b: [4 5]
a > b
[False False]
a >= b
[False False]
a < b
[ True True]
a <= b
[ True True]

Write a NumPy program to compare two arrays using NumPy.

Pictorial Presentation:
Sample Solution:

Python Code:
import numpy as np

a = np.array([1, 2])

b = np.array([4, 5])

print("Array a: ",a)

print("Array b: ",b)

print("a > b")

print(np.greater(a, b))

print("a >= b")

print(np.greater_equal(a, b))

print("a < b")

print(np.less(a, b))
print("a <= b")

print(np.less_equal(a, b))

Copy
Sample Output:
Array a: [1 2]
Array b: [4 5]
a > b
[False False]
a >= b
[False False]
a < b
[ True True]
a <= b
[ True True]
Write a NumPy program to sort along the first and last axes of an array.
Sample array: [[2,5],[4,4]]

Sample Solution:-

Python Code:
import numpy as np

a = np.array([[4, 6],[2, 1]])

print("Original array: ")

print(a)

print("Sort along the first axis: ")

x = np.sort(a, axis=0)

print(x)

print("Sort along the last axis: ")

y = np.sort(x, axis=1)

print(y)
Copy
Sample Output:
Expected Output:
Original array:
[[4 6]
[2 1]]
Sort along the first axis:
[[2 1]
[4 6]]
Sort along the last axis:
[[1 2]
[4 6]]

Write a NumPy program to get the values and indices of the elements that are
bigger than 10 in a given array.

Pictorial Presentation:

Sample Solution:-
Python Code:
import numpy as np

x = np.array([[0, 10, 20], [20, 30, 40]])

print("Original array: ")

print(x)

print("Values bigger than 10 =", x[x>10])

print("Their indices are ", np.nonzero(x > 10))

Copy
Sample Output:
Original array:
[[ 0 10 20]
[20 30 40]]
Values bigger than 10 = [20 20 30 40]
Their indices are (array([0, 1, 1, 1]), array([2, 0, 1, 2]))

Write a NumPy program to find the memory size of a NumPy array.

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np

n = np.zeros((4,4))

print("%d bytes" % (n.size * n.itemsize))

Copy
Sample Output:
128 bytes

Write a NumPy program to create an array of ones and zeros.

Sample Solution:-
Python Code:
import numpy as np

print("Create an array of zeros")

x = np.zeros((1,2))

print("Default type is float")

print(x)

print("Type changes to int")

x = np.zeros((1,2), dtype = np.int)

print(x)

print("Create an array of ones")

y= np.ones((1,2))

print("Default type is float")

print(y)

print("Type changes to int")

y = np.ones((1,2), dtype = np.int)

print(y)

Copy
Sample Output:
Create an array of zeros
Default type is float
[[ 0. 0.]]
Type changes to int
[[0 0]]
Create an array of ones
Default type is float
[[ 1. 1.]]
Type changes to int
[[1 1]]
Write a NumPy program to change an array's data type.

Sample Solution:-

Python Code:
import numpy as np

x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)

print(x)

print("Data type of the array x is:",x.dtype)

# Change the data type of x

y = x.astype(float)

print("New Type: ",y.dtype)

print(y)

Copy
Sample Output:
[[ 2 4 6]
[ 6 8 10]]
Data type of the array x is: int32
New Type: float64
[[ 2. 4. 6.]
[ 6. 8. 10.]]

Write a NumPy program to create a new array of 3*5, filled with 2.

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np
#using no.full

x = np.full((3, 5), 2, dtype=np.uint)

print(x)

#using no.ones

y = np.ones([3, 5], dtype=np.uint) *2

print(y)

Copy
Sample Output:
[[2 2 2 2 2]
[2 2 2 2 2]
[2 2 2 2 2]]
[[2 2 2 2 2]
[2 2 2 2 2]
[2 2 2 2 2]]

Write a NumPy program to concatenate two 2-dimensional arrays.


Sample arrays: ([[0, 1, 3], [5, 7, 9]], [[0, 2, 4], [6, 8, 10]]

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np

a = np.array([[0, 1, 3], [5, 7, 9]])

b = np.array([[0, 2, 4], [6, 8, 10]])

c = np.concatenate((a, b), 1)

print(c)

Copy
Sample Output:
[[ 0 1 3 0 2 4]
[ 5 7 9 6 8 10]]

Write a NumPy program to get the number of non-zero elements in an array.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])

print("Original array:")

print(x)

print("Number of non zero elements in the above array:")

print(np.count_nonzero(x))

Copy
Sample Output:
Original array:
[[ 0 10 20]
[20 30 40]]
Number of non zero elements in the above array:
5

Write a NumPy program to test if specified values are present in an array.

Pictorial Presentation:

Sample Solution:-
Python Code:
import numpy as np

x = np.array([[1.12, 2.0, 3.45], [2.33, 5.12, 6.0]], float)

print("Original array:")

print(x)

print(2 in x)

print(0 in x)

print(6 in x)

print(2.3 in x)

print(5.12 in x)

Copy
Sample Output:
Original array:
[[ 1.12 2. 3.45]
[ 2.33 5.12 6. ]]
True
False
True
False
True
Write a NumPy program to create a vector of size 10 with values ranging from 0
to 1, both excluded.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np

x = np.linspace(0,1,12,endpoint=True)[1:-1]

// [1:-1]: This slice notation is applied to the array x to remove the first element
(0.) and the last element (1.) of the array. The resulting array would look like this:
[0.09090909, 0.18181818, ..., 0.81818182, 0.90909091].
print(x)

Copy
Sample Output:
[ 0.09090909 0.18181818 0.27272727 0.36363636 0.45454545
0.54545455
0.63636364 0.72727273 0.81818182 0.90909091]
write a NumPy program (using numpy) to sum all the multiples of 3 or 5 below
100.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np

x = np.arange(1, 100)

# find multiple of 3 or 5

n= x[(x % 3 == 0) | (x % 5 == 0)]
print(n[:100])// print(n[:100]): This part prints the first 1000 elements of the
n array. Since there are fewer than 1000 elements in n, this will print all elements
in the array.
# print sum the numbers

print(n.sum())

Copy
Sample Output:
[ 3 5 6 9 10 12 15 18 20 21 24 25 27 30 33 35 36 39 40 42 45
48 50 5
1 54
55 57 60 63 65 66 69 70 72 75 78 80 81 84 85 87 90 93 95 96 99]
2318

Write a NumPy program to create a 5x5x5 cube of 1's.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np
x = np.zeros((5, 5, 5)).astype(int)

print(x)

Copy
Sample Output:
[[[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 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]]]

Write a NumPy program to convert a NumPy array of floating values to a numpy


array of integer values.

Pictorial Presentation:
Sample Solution:-

Python Code:
import numpy as np

x= np.array([[12.0, 12.51], [2.34, 7.98], [25.23, 36.50]])

print("Original array elements:")

print(x)

print("Convert float values to integer values:")


print(x.astype(int))

Copy
Sample Output:
Original array elements:
[[ 12. 12.51]
[ 2.34 7.98]
[ 25.23 36.5 ]]
Convert float values to integer values:
[[12 12]
[ 2 7]
[25 36]]

write a NumPy program to create a NumPy array of 10 integers from a generator.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np

iterable = (x for x in range(10))

print(np.fromiter(iterable, np.int))

Copy
Sample Output:
[0 1 2 3 4 5 6 7 8 9]

Write a NumPy program to add an extra column to a NumPy array.

Pictorial Presentation:

Sample Solution:-

Python Code:
import numpy as np

x = np.array([[10,20,30], [40,50,60]])

y = np.array([[100], [200]])

print(np.append(x, y, axis=1))

Copy
Sample Output:
[[ 10 20 30 100]
[ 40 50 60 200]]

Write a NumPy program to remove specific elements from a NumPy array.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np

x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

index = [0, 3, 4]

print("Original array:")
print(x)

print("Delete first, fourth and fifth elements:")

new_x = np.delete(x, index)

print(new_x)

Copy
Sample Output:
Original array:
[ 10 20 30 40 50 60 70 80 90 100]
Delete first, fourth and fifth elements:
[ 20 30 60 70 80 90 100]

Write a NumPy program to replace the negative values in a NumPy array with 0.

Pictorial Presentation:
Sample Solution:

Python Code:
import numpy as np

x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])

print("Original array:")

print(x)

print("Replace the negative values of the said array with 0:")

x[x < 0] = 0

print(x)

Sample Output:
Original array:
[-1 -4 0 2 3 4 5 -6]
Replace the negative values of the said array with 0:
[0 0 0 2 3 4 5 0]

Write a NumPy program to remove all rows in a NumPy array that contain non-
numeric values.

Pictorial Presentation:

Sample Solution:
Python Code:
import numpy as np

x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False,


True]])

print("Original array:")

print(x)

print("Remove all non-numeric elements of the said array")

print(x[~np.isnan(x).any(axis=1)])

Copy
Sample Output:
Original array:
[[ 1. 2. 3.]
[ 4. 5. nan]
[ 7. 8. 9.]
[ 1. 0. 1.]]
Remove all non-numeric elements of the said array
[[ 1. 2. 3.]
[ 7. 8. 9.]
[ 1. 0. 1.]]
Write a NumPy program to count the frequency of distinct values in a NumPy
array.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np

a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )

print("Original array:")

print(a)

unique_elements, counts_elements = np.unique(a,


return_counts=True)
print("Frequency of unique values of the said array:")

print(np.asarray((unique_elements, counts_elements)))

Copy
Sample Output:
Original array:
[10 10 20 10 20 20 20 30 30 50 40 40]
Frequency of unique values of the said array:
[[10 20 30 40 50]
[ 3 4 2 2 1]]

Write a NumPy program to print all array values.

Pictorial Presentation:

Sample Solution:

Python Code:
import numpy as np
np.set_printoptions(threshold=np.nan)

x = np.zeros((4, 4))

print(x)

Copy
Sample Output:
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
np.set_printoptions(threshold=np.nan): Set the print options in NumPy so that the
entire array will be printed without truncation, regardless of its size. The
'threshold' parameter is set to 'np.nan' to ensure that all elements are displayed.

x = np.zeros((4, 4)): This line creates a 4x4 NumPy array 'x' filled with zeros.

print(x): Print the 4x4 array 'x', with all elements displayed due to the print options
set earlier.

You might also like