Reputation: 244
I have a 2D array called my_array
. To select the 1st, 13th, 14th, 15th, and the 16th element from each row I use the following line
desired_elements = my_array[:,[0,12,13,14,15]]
This works, but I'm pretty sure that the [0,12,13,14,15]
part can be written more compactly. I have tried to look for a way, but until now I have been unable to do so.
Question: Is there a shorter way to write
desired_elements = my_array[:,[0,12,13,14,15]]
Upvotes: 1
Views: 59
Reputation: 2098
This is not shorter but equal in length for your specific input, but perhaps it is what you're looking for. You could be using np.r_
, which translates slice objects to concatenation along the first axis.
It's a simple way to build up arrays quickly when you have multiple slices to select.
Here's how you would do with your example:
desired_elements = my_array[:, np.r_[0, 12:16]]
Now, if you wanted to select more slices, you would probably end up with something shorter than the approach you take, for instance:
desired_elements = my_array[:, np.r_[0, 4:8, 11:14]]
May I ask why it is so critical to shorten your input?
Upvotes: 1