Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: How to find in dataframe object type columns which has numeric data?

In the dataframe, I am trying to find numeric data columns which has dtype as "object". I want to do it automated way rather then looking into actual data within the dataframe.

I tried this, but it didn't work:

for obj_feature in df.select_dtypes(include="object").columns:
    if df[obj_feature].str.isalpha == False:
        print("Numeric data columns", obj_feature)

DDL to generate Dataframe:

import pandas as pd

df = pd.DataFrame({'id': [1, 2, 3],
                  'A': ['Month', 'Year', 'Quater'],
                  'B' : ['29.85', '85.43', '33.87'],
                  'C' : [45, 22, 33.4]})

Sorry forgot to add this: Expected Output: Pick Dataframe columns, B since it has numeric data values, but it has 'object' dtype.

Thanks!

like image 487
Anku Avatar asked Oct 23 '25 19:10

Anku


1 Answers

You can use pandas.api.types.is_numeric_dtype:

from pandas.api.types import is_numeric_dtype
{c: is_numeric_dtype(df[c]) for c in df}

output:

{'id': True, 'A': False, 'B': False, 'C': True}

selecting the numeric columns:

Here use select_dtype:

df.select_dtypes('number')

output:

   id     C
0   1  45.0
1   2  22.0
2   3  33.4
like image 105
mozway Avatar answered Oct 26 '25 10:10

mozway