numpy selecting multiple columns excluding certain ones – concise way
Question:
I have a short question about indexing in numpy. I’m trying to select subset of columns of a 2D array. For example, if I wanted columns other than 3, 6 and 9, then I would plug in a list of indicies excluding those positions:
x = np.arange(20).reshape(2,10)
x[:, [i for i in range(len(x[0])) if i not in [3, 6, 9]]]
[[ 0 1 2 4 5 7 8]
[10 11 12 14 15 17 18]]
The method works but I was wondering if there’s more concise way of doing the same thing?
Answers:
One way is with numpy.delete()
import numpy as np
x = np.arange(20).reshape(2,10)
np.delete(x, [3,6,9], axis=1)
[[ 0 1 2 4 5 7 8]
[10 11 12 14 15 17 18]]
I have a short question about indexing in numpy. I’m trying to select subset of columns of a 2D array. For example, if I wanted columns other than 3, 6 and 9, then I would plug in a list of indicies excluding those positions:
x = np.arange(20).reshape(2,10)
x[:, [i for i in range(len(x[0])) if i not in [3, 6, 9]]]
[[ 0 1 2 4 5 7 8]
[10 11 12 14 15 17 18]]
The method works but I was wondering if there’s more concise way of doing the same thing?
One way is with numpy.delete()
import numpy as np
x = np.arange(20).reshape(2,10)
np.delete(x, [3,6,9], axis=1)
[[ 0 1 2 4 5 7 8]
[10 11 12 14 15 17 18]]