如何在python中删除数组的所有其他元素? (np.repeat()的反函数?) [英] How to remove every other element of an array in python? (The inverse of np.repeat()?)
本文介绍了如何在python中删除数组的所有其他元素? (np.repeat()的反函数?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个数组x,并执行np.repeat(x,2)
,则实际上是在复制该数组.
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?
它也应该与随机数组y一起工作:
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]
应该可以完成这项工作.在这里,第二个元素通过用1进行索引选择,然后以2的间隔取值.
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.
这篇关于如何在python中删除数组的所有其他元素? (np.repeat()的反函数?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文