SDG
SDG

Reputation: 2342

Trying to convert all columns that are objects to strings

There are quite a few questions that deal with converting a specific column or all columns, but not a specific few columns where the dtype is something specific. Now if I got data with some of the columns being objects, I would like to see those specific columns cast into strings.

I think I am currently doing something like:

for column in calls.columns:
    if calls[column].dtype == 'object':
        calls[column] = calls[column].astype(str)

But I am looking for a more pythonic way.

Upvotes: 0

Views: 525

Answers (2)

Bitzel
Bitzel

Reputation: 61

you might use the following code:

calls[calls.select_dtypes(include='object').columns] = calls.select_dtypes(include='object').astype(dtype='category')

Upvotes: 2

Myccha
Myccha

Reputation: 1018

Depending on the pandas version you have, "object" is the string type.

That said, you could do this:

df.astype({col: str for col in df.select_dtypes('object').columns})

Or equivalent:

df.astype({col: str for col, dtype in df.dtypes.items() if dtype=='object'})

Upvotes: 1

Related Questions