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

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

    How about just checking type for one of the values in the column? We've always had something like this:

    isinstance(x, (int, long, float, complex))
    

    When I try to check the datatypes for the columns in below dataframe, I get them as 'object' and not a numerical type I'm expecting:

    df = pd.DataFrame(columns=('time', 'test1', 'test2'))
    for i in range(20):
        df.loc[i] = [datetime.now() - timedelta(hours=i*1000),i*10,i*100]
    df.dtypes
    
    time     datetime64[ns]
    test1            object
    test2            object
    dtype: object
    

    When I do the following, it seems to give me accurate result:

    isinstance(df['test1'][len(df['test1'])-1], (int, long, float, complex))
    

    returns

    True
    

提交回复
热议问题