Home » Machine Learning » Numpy » 2D Numpy Arrays and Indexing

2D Numpy Arrays and Indexing

You can always reshape a 1D Numpy array into a 2D or higher-dimensional array using the reshape method. You can also use reshape to reduce the number of dimensions of your array, or you can use flatten to create a 1D array.

import numpy as np

values = np.arange(1, 7)
print(values)
print()

values = values.reshape(2, 3)
print(values)
print()

values = values.flatten()
print(values)
[1 2 3 4 5 6]

[[1 2 3]
 [4 5 6]]

[1 2 3 4 5 6]

Indexing 2D Arrays

Numpy has a nice syntax for slicing or indexing higher-dimensional arrays. The indices are simply separated by commas.

import numpy as np

values = np.arange(1, 17).reshape(4, 4)
print(values)
print()

# Value at row index 1, column index 2
print(values[1, 2])
print()

# Rows 0, 1 and 2; column 1
print(values[0:3, 1])

print()

# All rows, columns 1 and 3
print(values[:, [1, 3]])
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

7

[ 2  6 10]

[[ 2  4]
 [ 6  8]
 [10 12]
 [14 16]]

Leave a Reply

Blog at WordPress.com.

%d