0% found this document useful (0 votes)
3 views

7.numpy_fancy_indexing

The document provides examples of fancy indexing in NumPy, demonstrating how to access and modify array elements using integer arrays. It includes code snippets that show how to select specific elements and modify their values, highlighting the behavior of assignments in NumPy arrays. Additionally, it explains the implications of modifying values through fancy indexing with examples.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

7.numpy_fancy_indexing

The document provides examples of fancy indexing in NumPy, demonstrating how to access and modify array elements using integer arrays. It includes code snippets that show how to select specific elements and modify their values, highlighting the behavior of assignments in NumPy arrays. Additionally, it explains the implications of modifying values through fancy indexing with examples.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

07/02/2025, 21:12 numpy_fancy_indexing

In [5]: import numpy as np


rand = np.random.RandomState(42)
x = rand.randint(100,size=10)
print(x)
print([x[3],x[7],x[2]])
ind = [3,7,2]
print(x[ind])
ind1 = np.array([[3,7],[4,5]])
print(x[ind1])

[51 92 14 71 60 20 82 86 74 74]
[71, 86, 14]
[71 86 14]
[[71 86]
[60 20]]

In [10]: x=np.arange(12).reshape(3,4)
rows = np.array([0,1,2])
cols = np.array([2,1,3])
print(x[rows,cols])
# Notice that the first value in the result is X[0, 2], the second is X[1, 1],
# third is X[2, 3].
print(x[1,[2,0,1]])
print(x[1:,[2,0,1]])
print(type(x))

[ 2 5 11]
[6 4 5]
[[ 6 4 5]
[10 8 9]]
<class 'numpy.ndarray'>

In [12]: # Modifying Values with Fancy Indexing :


x = np.arange(10)
i = np.array([2, 1, 8, 4])
x[i] = 99
print(x)
x[i] -= 10
print(x)
# ex -2 :
x = np.zeros(10)
x[[0, 0]] = [4, 6]
print(x)
# Where did the 4 go? The result of this operation is to first assign x[0] = 4,
# by x[0] = 6. The result, of course, is that x[0] contains the value 6.
i = [2, 3, 3, 4, 4, 4]
x[i] += 1
print(x)

[ 0 99 99 3 99 5 6 7 99 9]
[ 0 89 89 3 89 5 6 7 89 9]
[6. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[6. 0. 1. 1. 1. 0. 0. 0. 0. 0.]

localhost:8924/doc/tree/numpy_fancy_indexing.ipynb? 1/1

You might also like