15

How can I convert an object dtype structure to a string dtype? The method below is not working and the column remains object after converting to a string with .astype

import pandas as pd
df = pd.DataFrame({'country': ['A', 'B', 'C', 'D', 'E']})

df.dtypes
#country    object
#dtype: object

df['county'] = df['country'].astype(str)

df.dtypes
#country    object
#dtype: object
1
  • 4
    pandas V 1.0 introduced StringDtype - check the docs for more info on dtypes. Commented Mar 7, 2020 at 20:29

3 Answers 3

16

object is the default container capable of holding strings, or any combination of dtypes.

If you are using a version of pandas < '1.0.0' this is your only option. If you are using pd.__version__ >= '1.0.0' then you can use the new experimental pd.StringDtype() dtype. Being experimental, the behavior is subject to change in future versions, so use at your own risk.

df.dtypes
#country    object

# .astype(str) and .astype('str') keep the column as object. 
df['country'] = df['country'].astype(str)
df.dtypes
#country    object

df['country'] = df['country'].astype(pd.StringDtype())
df.dtypes
#country    string
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing and the link to the reference manual. Adapted the example from the manual pd.Series(['abc', None, 'def'], dtype=pd.StringDtype()) . It worked when everything else failed, e.g. see here or here or here
10

I got it to work using 'string' instead of str

df['country'] = df['country'].astype('string')
df.dtypes
#country    string

1 Comment

Amazing - but what stopped/would stop str working - null values perhaps?
0

You are converting it to a str. non-null object is how pandas handles str in some cases.

Check out this article on pandas data types.

Check out the most recent official docs on dtypes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.