More NumPy functions#
NumPy has an enormous range of functionality, and we can only scratch the surface here.
However, here are a few examples of NumPy code for various tasks that you might commonly want to do with your code.
Creating Arrays#
NumPy provides various functions for generating arrays:
np.arange()
#
np.arange()
can be used to generate arrays that contain sequences of integers.
np.arange(5) # generate an array containing a sequence of integers
array([0, 1, 2, 3, 4])
np.arange(1, 6) # specify the start and stop points
array([1, 2, 3, 4, 5])
np.arange(2, 20, 2) # specify start, stop, and step size
array([ 2, 4, 6, 8, 10, 12, 14, 16, 18])
np.ones()
#
np.ones(10) # create an array of 10 ones
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
np.zeros()
#
np.zeros(10) # create an array of 10 zeros
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.linspace()#
np.linspace()
will create an array of evenly spaced values (as floats)
# Create an array of wavelengths for spectral analysis
wavelengths = np.linspace(400, 700, 31) # 31 points from 400 nm to 700 nm
print("Wavelengths (nm):", wavelengths)
Wavelengths (nm): [400. 410. 420. 430. 440. 450. 460. 470. 480. 490. 500. 510. 520. 530.
540. 550. 560. 570. 580. 590. 600. 610. 620. 630. 640. 650. 660. 670.
680. 690. 700.]
Note that np.linspace()
takes a third optional argument that specifies the number of values to generate. This is different to np.arange()
where the third optional argument specifies the step-size between values.