Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I need to use different functions to treat numeric columns and string columns. What I am doing now is really dumb:

allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns)

for y in allc:

    treat_numeric(agg[y])    

allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).columns)

for y in allc:

    treat_str(agg[y])    

Is there a more elegant way to do this? E.g.

for y in agg.columns:

    if(dtype(agg[y]) == 'string'):

          treat_str(agg[y])

    elif(dtype(agg[y]) != 'string'):

          treat_numeric(agg[y])

1 Answer

0 votes
by (41.4k points)

You can access the data-type of a column with dtype:

for y in agg.columns:

    if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):

          treat_numeric(agg[y])

    else:

          treat_str(agg[y])

If you want to learn more about Pandas then visit this Python Course designed by the industrial experts.

Browse Categories

...