In Pandas, how to filter a Series based on the type of the values?

前端 未结 3 524
逝去的感伤
逝去的感伤 2020-12-09 10:29

Given a Series like

import pandas as pd

s = pd.Series([\'foo\', \'bar\', 42])

I would like to obtain a \'sub-series\' p

相关标签:
3条回答
  • 2020-12-09 11:15

    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]
    
    0 讨论(0)
  • 2020-12-09 11:19

    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
    
    0 讨论(0)
  • 2020-12-09 11:32

    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.

    0 讨论(0)
提交回复
热议问题