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?

4 Answers

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.

1

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.

>>> 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.":

>>> 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. ]) 

Just cast it to a list:

my_list = list(array) 

You can then get all the list methods from there.

1

Looks like you want .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]) 
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy