0

origin array is like:

array([nan, nan, 'hello', ..., nan, 'N', 61.0], dtype=object)

How can I remove all string from this array and get a new array with dtype float?

I know I can do this using python list:

[i for i in x if type(i) == float]

but this way will change numpy.ndarray to list, is there a way to do this in numpy?

2
  • Wrap that list with np.array. Commented Mar 22, 2021 at 3:13
  • Working with an object dtype array does not save any time compared to a list. Both contain references to objects elsewhere in memory. The fast, numeric numpy methods are not available for this. Commented Mar 22, 2021 at 3:22

3 Answers 3

1

You can try something like below.

import numpy as np
a = array([np.nan, np.nan, 'hello', ..., np.nan, 'N', 61.0], dtype=object)
a = a[[isinstance(i, float) for i in a]]
Sign up to request clarification or add additional context in comments.

2 Comments

The where isn't needed.
I got it. fixed it
0

I am not seeing a way in pure numpy but if you are fine using pandas to return a numpy array:

import panadas as pd
import numpy as np

arr = np.array([np.nan, np.nan, 'hello', np.nan, 'N', 61.0], dtype=object)
pd.to_numeric(pd.Series(arr), errors='coerce').dropna().values

Comments

0

You can use np.fromiter():

a = np.array([np.nan, np.nan, 'hello', ..., np.nan, 'N', 61.0], dtype=object)
r = np.fromiter((x for x in a if type(x) == float), dtype=float)

print(r)
#[nan nan nan 61.]

To further remove nan values:

r = r[~np.isnan(r)]
#[61.]

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.