Python NumPy

Python Tutorial @ Home
Python Tutorial
Advance Python Tutorial

Python NumPy

What is Python NumPy
How to install Python NumPy
create a NumPy array
Add elements to an NumPy Array

Python Numpy 4

Find the index of a value

To find the index of value, we can use the where() method of the NumPy module. The where() method will also return the datatype.

import numpy as np
a=np.array([1, 2, 3, 4, 5])
n=np.where(a==5)
print("Element found at position/index ", n)
b=np.array([100,200,300,400,500,600,700])
n=np.where(b==300)
print("Element found at position/index ",n)
n=np.where(b==3000)
print("Element found at position/index ",n)
if(np.where(b==3000)==0):
    print("Element found at position/index ",n)
else:
    print("Element is not present")
Element found at position/index  (array([4], dtype=int32),)
Element found at position/index  (array([2], dtype=int32),)
Element found at position/index  (array([], dtype=int32),)
Element is not present

If you want to just get only the index and not the data type then we use the following code:

import numpy as np
a=np.array([1, 2, 3, 4, 5])
print(a)
b=np.where(a == 5)
print("Element found at position/index: ", b[0])
b=np.where(a == 2)
print("Element found at position/index: ", b[0])
a=np.array([100,200,300,400,500])
print(a)
b=np.where(a == 300)
print("Element found at position/index: ", b[0])
[1 2 3 4 5]
Element found at position/index:  [4]
Element found at position/index:  [1]
[100 200 300 400 500]
Element found at position/index:  [2]

NumPy array slicing

Array slicing is the process of extracting a subset from a given array. You can slice an array using the colon (:) operator and specify the starting and ending of the array index, for example:
array[from:to]
Example:

import numpy
a = numpy.array([1, 2, 3, 4, 5, 6, 7, 8,9,10])
print(a)
print("A subset of array a ")
print(a[2:5])
print(a[3:7])
print(a[:4])
print(a[4:])

Output:

A subset of array a 
[3 4 5]
[4 5 6 7]
[1 2 3 4]
[ 5  6  7  8  9 10]

using negative index slicing

If we want to extract the last three elements. We can do this by using negative slicing as follows:

import numpy
a = numpy.array([1, 2, 3, 4, 5, 6, 7, 8,9,10])
print(a)
print("A subset of array a ")
print(a[-2:])
print(a[-7:-3])
print(a[:-4])
print(a[-4:])

Output:

A subset of array a 
[ 9 10]
[4 5 6 7]
[1 2 3 4 5 6]
[ 7  8  9 10]

Visitor Counter

0183274