Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas astype(): str vs 'string' vs StringDtype

Lots of posts about object vs. string dtypes in pandas. I understand that distinction already, for the most part. What I don't understand is the difference between these three options:

some_series.astype(str)
some_series.astype('string')
some_series.astype(pd.StringDtype())
  • The first option converts dtype of Series to object type.
  • The second option preserves pd.NA (displays in Jupyter as <NA>), so a nullable string type.
  • The third seems to behave exactly the same as the second option, so far as I can tell: also a nullable string type.

Furthermore, if after executing astype() I check dtype of the second and third options, both return the same output: string[python].

For the sake of simplicity, can I just use astype('string') instead of astype(pd.StringDtype()) and get exactly the same behavior, including conversion of series with only ints/floats or of nullable versions of such numeric data types? Are both astype('string') and astype(pd.StringDtype()) mapped to StringDtype internally? I could not find clarity on this point within pandas documentation (or within other stackoverflow posts). Thanks for the help.

Using:

  • pandas 1.4.1
  • python 3.10.4
like image 996
Stephen Frost Avatar asked Aug 07 '26 07:08

Stephen Frost


1 Answers

Pandas documentation explains that 'string' is an alias for StringDtype. See at link below:
Pandas dtype aliases

like image 61
Stephen Frost Avatar answered Aug 09 '26 21:08

Stephen Frost