Skip to content Skip to sidebar Skip to footer

How To Remove All String Elements From A Numpy Object Array

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

Solution 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]]

Solution 2:

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

Solution 3:

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

Post a Comment for "How To Remove All String Elements From A Numpy Object Array"