How to get around counterintuitive numpy behavior

Viewed 44

consider the following:

foo = np.array(['a', 'b', 2])

bar = [x for x in foo if isinstance(x, str)]

Much to my surprise, what comes out is:

['a', 'b', '2']

So the 2 became a string. I understand that numpy is meant to deal with homogeneous arrays, but still, this is undesirable behavior, and would be nice to avoid. Suggestions?

2 Answers

Numpy assumes str dtype in your case. Pass the dtype explicitly, e.g.:

foo = np.array(['a', 'b', 2], dtype=object)
bar = [x for x in foo if isinstance(x, str)]

Im not sure whats your problem here, but I guess you want that list to only have strings/chars of letters/words?

import numpy as np
lst = ['a' ,'b', 2]
# ['a', 'b', 2]
foo = np.array([each for each in lst if str(each).isalpha()])
# array(['a', 'b'], dtype='<U1')

This ensures that only character will be in the bumpy array

Related