How to remove every other element of an array in python? (The inverse of np.repeat()?)
Question:
If I have an array x, and do an np.repeat(x,2)
, I’m practically duplicating the array.
>>> x = np.array([1,2,3,4])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
How can I do the opposite so that I end up with the original array?
It should also work with a random array y:
>>> y = np.array([1,7,9,2,2,8,5,3,4])
How can I delete every other element so that I end up with the following?
array([7, 2, 8, 3])
Answers:
y[1::2]
should do the job. Here the second element is chosen by indexing with 1, and then taken at an interval of 2.
I was having trouble with what if you asked for the input of an array by a user?
So making a function helped a lot:
def remove_every_other(my_list):
return my_list[::2]
pass
This helped me figure out that if any user were to enter in an array, we could handle it by calling this function.
If I have an array x, and do an np.repeat(x,2)
, I’m practically duplicating the array.
>>> x = np.array([1,2,3,4])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
How can I do the opposite so that I end up with the original array?
It should also work with a random array y:
>>> y = np.array([1,7,9,2,2,8,5,3,4])
How can I delete every other element so that I end up with the following?
array([7, 2, 8, 3])
y[1::2]
should do the job. Here the second element is chosen by indexing with 1, and then taken at an interval of 2.
I was having trouble with what if you asked for the input of an array by a user?
So making a function helped a lot:
def remove_every_other(my_list):
return my_list[::2]
pass
This helped me figure out that if any user were to enter in an array, we could handle it by calling this function.