How to determine whether a column/variable is numeric or not in Pandas/NumPy?

后端 未结 9 1983
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 02:47

Is there a better way to determine whether a variable in Pandas and/or NumPy is numeric or not ?

I have a self defined

相关标签:
9条回答
  • 2020-12-01 03:15

    In pandas 0.20.2 you can do:

    import pandas as pd
    from pandas.api.types import is_string_dtype
    from pandas.api.types import is_numeric_dtype
    
    df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [1.0, 2.0, 3.0]})
    
    is_string_dtype(df['A'])
    >>>> True
    
    is_numeric_dtype(df['B'])
    >>>> True
    
    0 讨论(0)
  • 2020-12-01 03:16

    This is a pseudo-internal method to return only the numeric type data

    In [27]: df = DataFrame(dict(A = np.arange(3), 
                                 B = np.random.randn(3), 
                                 C = ['foo','bar','bah'], 
                                 D = Timestamp('20130101')))
    
    In [28]: df
    Out[28]: 
       A         B    C                   D
    0  0 -0.667672  foo 2013-01-01 00:00:00
    1  1  0.811300  bar 2013-01-01 00:00:00
    2  2  2.020402  bah 2013-01-01 00:00:00
    
    In [29]: df.dtypes
    Out[29]: 
    A             int64
    B           float64
    C            object
    D    datetime64[ns]
    dtype: object
    
    In [30]: df._get_numeric_data()
    Out[30]: 
       A         B
    0  0 -0.667672
    1  1  0.811300
    2  2  2.020402
    
    0 讨论(0)
  • 2020-12-01 03:16

    You can also try:

    df_dtypes = np.array(df.dtypes)
    df_numericDtypes= [x.kind in 'bifc' for x in df_dtypes]
    

    It returns a list of booleans: True if numeric, False if not.

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