Matrices or one of the most useful structures to use in mathematics. While numpy does have a matrix data structure, it is more common to use a 2d array using the baisc np.array
method. In this article, we will see how to select items from 2d arrays in numpy.
In our example below, we start by creating a 2d array with 3 rows and 3 columns.
2d = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
No, we see how to select rows. We can us normal array index notation, but we will receive rows back instead of indiviual elements.
# Select the first row
print(2d[0])
# Select the second row
print(2d[1])
# Select up to the first row
print(2d[:1])
Finally, we see how to select rows and columns. The notation is similar, but we add an extra selector after a comma. We can also use the slice operator to select multiple rows and columns.
# Select the first row, second column
print(2d[0, 1])
# Select the first two rows, second and third columns
print(2d[:2, 1:])