Python – Numpy Indexing, Slicing, and Iterating

In NumPy one-dimensional arrays can be indexed, sliced, and iterated over much like lists in Python.

import numpy as np

a = np.arange(10)**3

#prints: [  0   1   8  27  64 125 216 343 512 729]
print(a)

#prints the third element in the array: 8 
print(a[2])

#prints the third element to the sixth element: [ 8 27 64]
print(a[2:5])

#inserts -1000 into the array: [-1000     1 -1000    27 -1000   125   216   343   512   729]
a[:6:2] = -1000

print(a)

#inverts the array: [  729   512   343   216   125 -1000    27 -1000     1 -1000]
print(a[: :-1])

#will return warning: 22: RuntimeWarning: invalid value encountered in power
for i in a: 
	print(i**(1/3.))

#prints the folowing: 
# nan
# 1.0
# nan
# 3.0
# nan
# 5.0
# 6.0
# 7.0
# 8.0
# 9.0

**This article is written for Python 3.6

Multidimensional arrays can have one index per axis.


import numpy as np

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

print("This is your multidimensional test array:") 
print(multiDimArr)

print("This is the second element in the first array:")
print(multiDimArr[0,1])

<< Numpy Dot Product

%d bloggers like this: