从数组中删除元素

从数组中删除元素

本文介绍了从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组,我想删除该数组的前3个元素.我尝试了这种解决方案:

I have a numpy array and I want to delete the first 3 elements of the array. I tried this solution:

           a = np.arange(0,10)
           i=0
           while(i<3):
             del a[0]
             i=i+1

这给我一个错误,提示" ValueError:无法删除数组元素".我不明白为什么会这样.感谢您的帮助!

This gives me an error that "ValueError: cannot delete array elements". I do not understand why this is the case. i'd appreciate the help thanks!

推荐答案

Numpy数组的大小是固定的,因此不能简单地从其中删除元素.实现所需目标的最简单方法是使用切片:

Numpy arrays have a fixed size, hence you cannot simply delete an element from them. The simplest way to achieve what you want is to use slicing:

a = a[3:]

这将从原始数组的第4个元素开始创建一个新数组.

This will create a new array starting with the 4th element of the original array.

在某些情况下,切片仅仅是不够的.如果要创建由原始数组中的特定元素组成的子数组,则可以使用另一个数组来选择索引:

For certain scenarios, slicing is just not enough. If you want to create a subarray consisting of specific elements from the original array, you can use another array to select the indices:

>>> a = arange(10, 20)
>>> a[[1, 4, 5]]
array([11, 14, 15])

因此,基本上,a[[1,4,5]]将返回一个由原始数组的元素1,4和5组成的数组.

So basically, a[[1,4,5]] will return an array that consists of the elements 1,4 and 5 of the original array.

这篇关于从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:56