Skip to content

Commit 1b57f67

Browse files
committed
add section on selecting one element from each row of an array
1 parent a394e18 commit 1b57f67

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

python-numpy-tutorial.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,6 @@ print a[[0, 1, 2], [0, 1, 0]] # Prints "[1 4 5]"
559559
# The above example of integer array indexing is equivalent to this:
560560
print np.array([a[0, 0], a[1, 1], a[2, 0]]) # Prints "[1 4 5]"
561561

562-
563562
# When using integer array indexing, you can reuse the same
564563
# element from the source array:
565564
print a[[0, 0], [1, 1]] # Prints "[2 2]"
@@ -568,6 +567,35 @@ print a[[0, 0], [1, 1]] # Prints "[2 2]"
568567
print np.array([a[0, 1], a[0, 1]]) # Prints "[2 2]"
569568
```
570569

570+
One useful trick with integer array indexing is selecting or mutating one
571+
element from each row of a matrix:
572+
573+
```python
574+
import numpy as np
575+
576+
# Create a new array from which we will select elements
577+
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
578+
579+
print a # prints "array([[ 1, 2, 3],
580+
# [ 4, 5, 6],
581+
# [ 7, 8, 9],
582+
# [10, 11, 12]])"
583+
584+
# Create an array of indices
585+
b = np.array([0, 2, 0, 1])
586+
587+
# Select one element from each row of a using the indices in b
588+
print a[np.arange(4), b] # Prints "[ 1 6 7 11]"
589+
590+
# Mutate one element from each row of a using the indices in b
591+
a[np.arange(4), b] += 10
592+
593+
print a # prints "array([[11, 2, 3],
594+
# [ 4, 5, 16],
595+
# [17, 8, 9],
596+
# [10, 21, 12]])
597+
```
598+
571599
**Boolean array indexing:**
572600
Boolean array indexing lets you pick out arbitrary elements of an array.
573601
Frequently this type of indexing is used to select the elements of an array

0 commit comments

Comments
 (0)