Edamame
Edamame

Reputation: 25366

Change data type of a column from object to string in pandas

I have a data frame my_df:

my_df.dtypes

time           int64
fieldA         object
fieldB         object
fieldC         object
fieldD         object
fieldE         object
dtype: object

I tried to change the fieldB and fieldC to type string by doing:

my_df[['fieldB','fieldC']] = my_df[['fieldB','fieldC']].astype(str)

After the above is finished, I tried to run my_df.dtypes again, but nothing is changed to string ...

Does anyone know what I missed? Thanks!

Upvotes: 0

Views: 1825

Answers (1)

Jezzamon
Jezzamon

Reputation: 1491

Pandas only has a few specific data types that mainly handle numeric values. For everything else it uses the object type. Strings fit into the latter category, and so it is likely that your data is already strings, even though the data type is listed as object.

The different types are listed in the documentation:

The main types stored in pandas objects are float, int, bool, datetime64[ns] and datetime64[ns, tz] (in >= 0.17.0), timedelta[ns], category (in >= 0.15.0), and object.

Upvotes: 1

Related Questions