Pandas select only numeric or integer field from dataframe

后端 未结 4 1795
栀梦
栀梦 2021-01-11 19:17

I have this Pandas dataframe (df):

     A    B
0    1    green
1    2    red
2    s    blue
3    3    yellow
4    b    black

A type is obje

4条回答
  •  执笔经年
    2021-01-11 19:58

    You can use convert_objects, which when convert_numeric=True will forcefully set all non-numeric to nan. Dropping them and indexing gets your result.

    This will be considerably faster that using apply on a larger frame as this is all implemented in cython.

    In [30]: df[['A']].convert_objects(convert_numeric=True)
    Out[30]: 
        A
    0   1
    1   2
    2 NaN
    3   3
    4 NaN
    
    In [31]: df[['A']].convert_objects(convert_numeric=True).dropna()
    Out[31]: 
       A
    0  1
    1  2
    3  3
    
    In [32]: df[['A']].convert_objects(convert_numeric=True).dropna().index
    Out[32]: Int64Index([0, 1, 3], dtype='int64')
    
    In [33]: df.iloc[df[['A']].convert_objects(convert_numeric=True).dropna().index]
    Out[33]: 
       A       B
    0  1   green
    1  2     red
    3  3  yellow
    

提交回复
热议问题