Indexing and slicing unidimensional arrays

5.10. Indexing and slicing unidimensional arrays#

Indexing and slicing a unidimensional array is identical to indexing and slicing a Python list.

Tip

As a reminder:

  • Indexing means accessing one element using an index: the_array[2]

  • Slicing means accessing several elements using a slice: the_array[0:3]

Through this section, we will work with two example arrays:

  • data: some random data;

  • time: the corresponding time.

import numpy as np
import matplotlib.pyplot as plt

data = np.array([0.0, 0.58, 0.95, 0.95, 0.58, 0.0, -0.59, -0.96, -0.96, -0.59])
time = np.arange(10) / 10

plt.plot(time, data, "s-")
plt.grid(True);
_images/21ce2ab225b089ace2aea702a3a1c61d1daa9245d0c8b666d14fe310894e0ed0.png

As mentioned above, indexing a unidimensional array is identical to indexing a list. To read one element of a list/array:

data[2]  # Read the 3rd element
0.95

To write one element of a list/array:

data[2] = 0.58  # Assign 0.35 to the 3rd element

# Plot the result
plt.plot(time, data, "s-")
plt.grid(True)

data[2] = 0.95  # Reset to its original value
_images/bc7a711e7205802022b587568340433941a19e43273a5ac77a2032acde99680e.png

Negative indexing also works:

# Read the last data
data[-1]
-0.59

Slicing a unidimentional array is identical to slicing a list. To read several elements of a list/array:

# Keep only the values at indexes 2, 4, 6 and 8 of the original array
# Start at 2 (incl.), up to 9 (excl.) by steps of 2:
data_subset = data[2:9:2]
time_subset = time[2:9:2]

# Plot the result
plt.plot(time, data, "s-", label="original data")
plt.plot(time_subset, data_subset, "o-", label="subset")
plt.grid(True)
plt.legend();
_images/bb7b8990dfbfff9adbd034f60301c8f2a94601db986c200861e730c5bad2684a.png

To write several elements of a list/array:

# Replace values at indexes 2, 4, 6, 8 of the original list/array by
# [-0.7, -0.8, -0.9, -1.0]

modified_data = data.copy()
modified_data[2:9:2] = [-0.7, -0.8, -0.9, -1.0]

# Plot the result
plt.plot(time, data, "s-", label="original data")
plt.plot(time, modified_data, "o-", label="modified data")
plt.grid(True)
plt.legend();
_images/2855ffe9282aee7b1103ab7e85f588111d8f626829c9f2b2edaa62535b14a3da.png

Tip

Note the line

modified_data = data.copy()

Using the copy method is required here, because otherwise we are just telling Python to assign an additional name (modified_data) to the same variable (data). In this case, modifiying modified_data would also modify data since they are both the same array. Using the copy method creates a new, unique array so that modifying one won’t modify the other.