2

I have a numpy array with a mix of different dtypes: floats, ints and strings. I want to convert all floats and ints to floats, while leaving non-numeric entries untouched. Currently, when I do:

array = np.array(['1', '2', '3', 'string'])
array.astype(np.float64)

I get the following error:

ValueError: could not convert string to float: 'string'

I'd like for the output to look like this:

np.array([1.0, 2.0, 3.0, 'string'])

I've tried pd.is_numeric() as well, but can't figure it out. Is this feasible, or does it violate the rules of numpy arrays?

0

1 Answer 1

3

Your desired result is impossible since np.arrays can only have one data type (which would usually be one of the numerical types, e.g. float, int,...)... unless you choose the generic type dtype=object, but then you loose all the numpy goodness (i.e. all the optimization working on numerical values). So why do you want to do this?

If this is really what you want then try this:

array = np.array(['1', '2', '3', 'string'])

def safe_float(x):
    try:
        x = float(x)
    except:
        pass
    return x

array = np.array(list(map(safe_float, array)), dtype=object)
print(array)

array([1.0, 2.0, 3.0, 'string'], dtype=object)
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.