Python 'numpy.ndarray' 对象没有属性 'remove'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30197943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:03:32  来源:igfitidea点击:

'numpy.ndarray' object has no attribute 'remove'

pythonnumpymultidimensional-arrayfloating-point

提问by berkelem

I have an array of arrays and I'm trying to find the lowest non-zero value among them all.

我有一个数组数组,我试图在它们中找到最低的非零值。

minima = []
for array in K: #where K is my array of arrays (all floats)
    if 0.0 in array:
        array.remove(0.0)
    minima.append(min(array))

print min(minima)

This yields

这产生

AttributeError: 'numpy.ndarray' object has no attribute 'remove'

I thought array.remove()was the way to remove an element. What am I doing wrong?

我认为array.remove()是删除元素的方法。我究竟做错了什么?

采纳答案by berkelem

I think I've figured it out. The .remove()method is a list method, not an ndarray method. So by using array.tolist()I can then apply the .remove()method and get the required result.

我想我已经想通了。该.remove()方法是一个列表方法,而不是一个 ndarray 方法。因此,通过使用array.tolist()我可以应用该.remove()方法并获得所需的结果。

回答by hd1

Looks like you want .delete:

看起来你想要 .delete

minima = []
for array in K: #where K is my array of arrays (all floats)
    minimum = min(array)
    minima = np.delete(array, minimum)
    minima.append(min(array))

print(minima)

And it seems to work for me, hence:

它似乎对我有用,因此:

In [5]: a = np.array([1,3,5])                                                                                                                                   

In [6]: a = np.delete(a, 0)                                                                                                                                         

In [7]: a
Out[7]: array([3, 5])

回答by Sinister Beard

Just cast it to a list:

只需将其转换为列表:

my_list = list(array)

You can then get all the listmethods from there.

然后,您可以list从那里获取所有方法。

回答by JDQ

This does not directly address your question, as worded, but instead condenses some of the points made in the other answers/comments.

这并不像措辞那样直接解决您的问题,而是浓缩了其他答案/评论中提出的一些观点。



The following demonstrates how to, effectively, remove the value 0.0 from a NumPy array.

下面演示了如何有效地从 NumPy 数组中删除值 0.0。

>>> import numpy as np
>>> arr = np.array([0.1, 0.2, 0.0, 1.0, 0.0]) # NOTE: Works if more than one value == 0.0
>>> arr
array([0.1, 0.2, 0. , 1. , 0. ])
>>> indices = np.where(arr==0.0)
>>> arr = np.delete(arr, indices)
>>> arr
array([0.1, 0.2, 1. ])

Another useful method is numpy.unique(), which, "Returns the sorted unique elements of an array.":

另一个有用的方法是numpy.unique(),它“返回数组的排序后的唯一元素。”:

>>> import numpy as np
>>> arr = np.array([0.1, 0.2, 0.0, 1.0, 0.0])
>>> arr = np.unique(arr)
>>> arr
array([0. , 0.1, 0.2, 1. ])