2

I'm using the numpy.delete function to remove elements from several arrays. I started from this question Make this simple for/if block more pythonic and arrived, after applying the answer given there, to this:

# Data lists.
a = [3,4,5,12,6,8,78,5,6]
b = [6,4,1.,2,8,784.,43,6.,2]
c = [8,4.,32.,6,1,7,2.,9,23]

# Maximum limit.
max_limit = 20.

# Store indexes of elements to be removed.
indexes = [i for i, t in enumerate(zip(b, c)) if any(e > max_limit for e in t)]

# Remove elements from all lists.
big_array = np.array([a, b, c])
clean_array = np.delete(big_array, indexes, axis=1)

# Final clean lists.
a_clean, b_clean, c_clean = clean_array

The issue I'm having is that one of my lists is actually made of strings rather than floats, like this:

# Data lists.
a = ['a','b','c','d','e','f','g','h','i'] # <-- strings
b = [6,4,1.,2,8,784.,43,6.,2] # <-- floats
c = [8,4.,32.,6,1,7,2.,9,23] # <-- floats

and when I apply the code above the numpy.delete line converts all elements in all final lists (a_clean, b_clean, c_clean) to strings rather than preserving only the first one as strings and the rest as floats.

How can I prevent this from happening or fix it if it can't be helped?

1 Answer 1

1

If you are going to use numpy, you are going to be better off converting your lists to arrays. It would look something like:

a = np.array(a)
b = np.array(b)
c = np.array(c)

mask = (b > max_limit) | (c > max_limit)

a = a[mask]
b = b[mask]
c = c[mask]

>>> a
array(['c', 'f', 'g', 'i'],
      dtype='|S1')
>>> b
array([   1.,  784.,   43.,    2.])
>>> c
array([ 32.,   7.,   2.,  23.])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.