I have a 40000 by 60 Numpy array, and I want to sth like this:
mat[:,[0:13,19:23,23:31,39:59]]
Obviously, it does not work. Is there a smarter way to do this than concatenation?
Use NumPy array indexing to extract specific columsUse the syntax array[:, [i, j]] to extract the i and j indexed columns from array . Like lists, NumPy arrays use zero-based indexes. Use array[:, i:j+1] to extract the i through j indexed columns from array .
The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
A colon by itself means fetch everything. A colon on the right side of an index means everything after the specified index. A colon on the left side of an index means everything before, but not including, the index. And if we use a negative index, it means get elements from the end, going backwards.
Use np.r_
-
mat[:,np.r_[0:13,19:23,23:31,39:59]]
Sample run -
In [48]: mat = np.random.rand(100,1000)
In [50]: mat[:,np.r_[0:13,19:23,23:31,39:59]].shape
Out[50]: (100, 45)
In [51]: 13+4+8+20
Out[51]: 45
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With