Given a Series
like
import pandas as pd
s = pd.Series([\'foo\', \'bar\', 42])
I would like to obtain a \'sub-series\' p
Use apply
or list comprehension:
s[s.apply(lambda x: isinstance(x, str))]
Same as, thanks Jon Clements♦
:
s[s.apply(isinstance, args=(str,))]
s[[isinstance(x, str) for x in s]]
All return:
0 foo
1 bar
dtype: object
EDIT:
This is not recommended, thanks cᴏʟᴅsᴘᴇᴇᴅ:
s[s.apply(type) == str]
I'd use pd.to_numeric
as pointed above.
Alternatively, you can use str.isalpha
In [109]: s[s.str.isalpha().notnull()]
Out[109]:
0 foo
1 bar
dtype: object
A little trick with pd.to_numeric
:
s[pd.to_numeric(s, errors='coerce').isnull()]
0 foo
1 bar
dtype: object
If an item is numeric, it is successfully coerced (not NaN
) and so is dropped from the final result.