Colab Notebook

Swap rows/columns

import numpy as np

a = np.arange(9).reshape(3, 3)

# Create a view of "a" with column 1 and 2 swapped
print(a[:, [1, 0, 2]])
# Prints [[3, 4, 5],
#         [0, 1, 2],
#         [6, 7, 8]]

# Create a view of "a" with rows 1 and 2 swapped
print(a[[1, 0, 2], :])
# Prints [[3, 4, 5],
#         [0, 1, 2],
#         [6, 7, 8]]
# or simply, a[[1, 0, 2]]
# If you're confused about the notation a[[1, 0, 2]] 
# is shorthand for a[[1, 0, 2], :] 

# Swap rows in-place
a[[0, 1]] = a[[1, 0]]
# Again, a[[0, 2]] is shorthand for a[[0, 2], :] 
# so this selects the submatrix consisting of 
# rows 0 and 2. 

# Swap columns in-place
a[:, [0, 1]] = a[:, [1, 0]]

Reverse rows

import numpy as np

a = np.arange(9).reshape(3, 3)

print(a[::-1])
# Prints [[6, 7, 8],
#         [3, 4, 5],
#         [0, 1, 2]]

Reverse columns

import numpy as np

a = np.arange(9).reshape(3, 3)

print(a[:, ::-1])
# Prints [[2, 1, 0],
#         [5, 4, 3],
#         [8, 7, 6]]

Filter array based on two or more conditions

import numpy as np

a = np.arange(9).reshape(3, 3)

a[(a > 1) & (a < 5)] = 0
print(a)
# Prints [[0 1 0]
# 		  [0 0 5]
# 		  [6 7 8]]

Find if a given array has any null values

import numpy as np

a = np.arange(9).reshape(3, 3)
print(np.isnan(a))
# Prints [[False False False]
#		  [False False False]
#		  [False False False]]
print(np.isnan(a).any())

a[]
print(np.isnan(a).any())

References and credits

Citation

If you found our work useful, please cite it as:

@article{Chadha2020DistilledNumPyTips,
  title   = {NumPy Tips},
  author  = {Chadha, Aman},
  journal = {Distilled AI},
  year    = {2020},
  note    = {\url{https://aman.ai}}
}