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

后端 未结 9 1991
佛祖请我去吃肉
佛祖请我去吃肉 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 02:51

    Based on @jaime's answer in the comments, you need to check .dtype.kind for the column of interest. For example;

    >>> import pandas as pd
    >>> df = pd.DataFrame({'numeric': [1, 2, 3], 'not_numeric': ['A', 'B', 'C']})
    >>> df['numeric'].dtype.kind in 'biufc'
    >>> True
    >>> df['not_numeric'].dtype.kind in 'biufc'
    >>> False
    

    NB The meaning of biufc: b bool, i int (signed), u unsigned int, f float, c complex. See https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.kind.html#numpy.dtype.kind

提交回复
热议问题