A new answer to reflect the most current practices: as of now (v1.2.4), neither astype('str') nor astype(str) work.

As per the documentation, a Series can be converted to the string datatype in the following ways:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

End to end example:

import pandas as pd

# Create a sample DataFrame
data = {
    'Name': ['John', 'Alice', 'Bob', 'John', 'Alice'],
    'Age': [25, 30, 35, 25, 30],
    'City': ['New York', 'London', 'Paris', 'New York', 'London'],
    'Salary': [50000, 60000, 70000, 50000, 60000],
    'Category': ['A', 'B', 'C', 'A', 'B']
}

df = pd.DataFrame(data)

# Print the DataFrame
print("Original DataFrame:")
print(df)
print("\nData types:")
print(df.dtypes)
cat_cols_ = None
# Apply the code to change data types
if not cat_cols_:
    # Get the columns with object data type
    object_columns = df.select_dtypes(include=['object']).columns.tolist()
    
    if len(object_columns) > 0:
        print(f"\nObject columns found, converting to string: {object_columns}")
        
        # Convert object columns to string type
        df[object_columns] = df[object_columns].astype('string')
    
    # Get the categorical columns (including string and category data types)
    cat_cols_ = df.select_dtypes(include=['category', 'string']).columns.tolist()

# Print the updated DataFrame and data types
print("\nUpdated DataFrame:")
print(df)
print("\nUpdated data types:")
print(df.dtypes)
print(f"\nCategorical columns (cat_cols_): {cat_cols_}")
Original DataFrame:
    Name  Age      City  Salary Category
0   John   25  New York   50000        A
1  Alice   30    London   60000        B
2    Bob   35     Paris   70000        C
3   John   25  New York   50000        A
4  Alice   30    London   60000        B

Data types:
Name        object
Age          int64
City        object
Salary       int64
Category    object
dtype: object

Object columns found, converting to string: ['Name', 'City', 'Category']

Updated DataFrame:
    Name  Age      City  Salary Category
0   John   25  New York   50000        A
1  Alice   30    London   60000        B
2    Bob   35     Paris   70000        C
3   John   25  New York   50000        A
4  Alice   30    London   60000        B

Updated data types:
Name        string[python]
Age                  int64
City        string[python]
Salary               int64
Category    string[python]
dtype: object

Categorical columns (cat_cols_): ['Name', 'City', 'Category']
Answer from rocksNwaves on Stack Overflow
Top answer
1 of 11
251

A new answer to reflect the most current practices: as of now (v1.2.4), neither astype('str') nor astype(str) work.

As per the documentation, a Series can be converted to the string datatype in the following ways:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

End to end example:

import pandas as pd

# Create a sample DataFrame
data = {
    'Name': ['John', 'Alice', 'Bob', 'John', 'Alice'],
    'Age': [25, 30, 35, 25, 30],
    'City': ['New York', 'London', 'Paris', 'New York', 'London'],
    'Salary': [50000, 60000, 70000, 50000, 60000],
    'Category': ['A', 'B', 'C', 'A', 'B']
}

df = pd.DataFrame(data)

# Print the DataFrame
print("Original DataFrame:")
print(df)
print("\nData types:")
print(df.dtypes)
cat_cols_ = None
# Apply the code to change data types
if not cat_cols_:
    # Get the columns with object data type
    object_columns = df.select_dtypes(include=['object']).columns.tolist()
    
    if len(object_columns) > 0:
        print(f"\nObject columns found, converting to string: {object_columns}")
        
        # Convert object columns to string type
        df[object_columns] = df[object_columns].astype('string')
    
    # Get the categorical columns (including string and category data types)
    cat_cols_ = df.select_dtypes(include=['category', 'string']).columns.tolist()

# Print the updated DataFrame and data types
print("\nUpdated DataFrame:")
print(df)
print("\nUpdated data types:")
print(df.dtypes)
print(f"\nCategorical columns (cat_cols_): {cat_cols_}")
Original DataFrame:
    Name  Age      City  Salary Category
0   John   25  New York   50000        A
1  Alice   30    London   60000        B
2    Bob   35     Paris   70000        C
3   John   25  New York   50000        A
4  Alice   30    London   60000        B

Data types:
Name        object
Age          int64
City        object
Salary       int64
Category    object
dtype: object

Object columns found, converting to string: ['Name', 'City', 'Category']

Updated DataFrame:
    Name  Age      City  Salary Category
0   John   25  New York   50000        A
1  Alice   30    London   60000        B
2    Bob   35     Paris   70000        C
3   John   25  New York   50000        A
4  Alice   30    London   60000        B

Updated data types:
Name        string[python]
Age                  int64
City        string[python]
Salary               int64
Category    string[python]
dtype: object

Categorical columns (cat_cols_): ['Name', 'City', 'Category']
2 of 11
127

You can convert all elements of id to str using apply

df.id.apply(str)

0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610

Edit by OP:

I think the issue was related to the Python version (2.7.), this worked:

df['id'].astype(basestring)
0        123
1        512
2      zhub1
3    12354.3
4        129
5        753
6        295
7        610
Name: id, dtype: object
Discussions

DISCUSSION: Add format parameter to .astype when converting to str dtype
I propose adding a string formatting possibility to .astype when converting to str dtype: I think it's reasonable to expect that you can choose the string format when converting to a string dty... More on github.com
🌐 github.com
19
August 10, 2017
BUG: pandas 1.1.0 MemoryError using .astype("string") which worked using pandas 1.0.5
I have checked that this issue has not already been reported. I have confirmed this bug exists on the latest version of pandas. (optional) I have confirmed this bug exists on the master branch of p... More on github.com
🌐 github.com
9
July 31, 2020
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.astype.html
pandas.Series.astype — pandas 3.0.2 documentation - PyData |
>>> ser = pd.Series([1, 2], dtype="int32") >>> ser 0 1 1 2 dtype: int32 >>> ser.astype("int64") 0 1 1 2 dtype: int64
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-series-astype-to-convert-data-type-of-series
Python | Pandas Series.astype() to convert Data type of series - GeeksforGeeks
July 11, 2025 - Syntax: DataFrame.astype(dtype, copy=True, errors='raise') Parameters: dtype: Data type to convert the series into. (for example str, float, int) copy: Makes a copy of dataframe/series. errors: Error raising on conversion to invalid data type. For example dict to string.
🌐
Medium
medium.com › @bacharliav › boosting-memory-efficiency-in-pandas-replacing-astype-str-with-convert-dtypes-1e7675ceca76
Boosting Memory Efficiency in Pandas: Replacing “astype(str)” with “convert_dtypes” | by Bacharliav | Medium
June 30, 2023 - This function not only retains ... handles string data and missing values more efficiently. However, situations involving mixed data type columns and Parquet file saving may still require astype(str). Knowledge of tools like pd.convert_dtypes() is instrumental in enhancing memory efficiency in Python and ...
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: How to use astype() to cast dtype of DataFrame | note.nkmk.me
August 9, 2023 - If you read the file without specifying dtype and then cast it to str with astype(), NaN values are also converted to the string 'nan'.
🌐
W3Schools
w3schools.com › python › pandas › ref_df_astype.asp
Pandas DataFrame astype() Method
The astype() method returns a new DataFrame where the data types has been changed to the specified type. You can cast the entire DataFrame to one specific data type, or you can use a Python Dictionary to specify a data type for each column, ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-dataframe-astype
Pandas DataFrame.astype()-Python - GeeksforGeeks
June 26, 2025 - Explanation: astype('string') converts all DataFrame columns to string type, ensuring that all values, whether integers or floats, are treated as strings.
🌐
Saturn Cloud
saturncloud.io › blog › python-pandas-converting-object-to-string-type-in-dataframes
Python Pandas: Converting Object to String Type in DataFrames | Saturn Cloud Blog
October 26, 2023 - To convert column B from object to string, we use the astype() function, which is a function that converts the data type of a Pandas Series.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.astype.html
pandas.DataFrame.astype — pandas 3.0.2 documentation
>>> ser = pd.Series([1, 2], dtype="int32") >>> ser 0 1 1 2 dtype: int32 >>> ser.astype("int64") 0 1 1 2 dtype: int64
🌐
DEV Community
dev.to › atifwattoo › what-is-astype-function-in-python-4bg5
What is astype() function in Python - DEV Community
January 8, 2025 - import pandas as pd # Original DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.1, 2.2, 3.3]}) print("Original memory usage:") print(df.memory_usage()) # Downcast numerical types df['A'] = df['A'].astype('int8') df['B'] = df['B'].astype('float32') print("Optimized memory usage:") print(df.memory_usage()) ... Column A as int64 uses 24 bytes (8 bytes per element × 3 elements). Column B as float64 uses 24 bytes (8 bytes per element × 3 elements). ... Column A as int8 uses 3 bytes (1 byte per element × 3 elements). Column B as float32 uses 12 bytes (4 bytes per element × 3 elements). Invalid Conversion: Converting incompatible types (e.g., strings to numeric types when non-numeric values exist).
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert column to string type
Pandas Convert Column to String Type - Spark By {Examples}
July 3, 2025 - Tags: DataFrame.apply(str), DataFrame.applymap(str), DataFrame.astype(str), DataFrame.map(str), DataFrame.values.astype(str)
🌐
GitHub
github.com › pandas-dev › pandas › issues › 17211
DISCUSSION: Add format parameter to .astype when converting to str dtype · Issue #17211 · pandas-dev/pandas
August 10, 2017 - This possibility should take shape of a format parameter to .astype, that can take a string and can only be used when converting to string dtype.
Author   topper-123
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › pandas-convert-column-to-string-type
Pandas Convert Column To String Type - GeeksforGeeks
July 23, 2025 - .astype(data_Type) Let us understand this using an example: Here we define that the numeric type for the dataset should be converted to a string (Str). This will convert the data type “int” to "string.”. Python ·
🌐
Medium
medium.com › @heyamit10 › understanding-pandas-astype-with-examples-f1b21ad17e69
Understanding pandas astype() with Examples | by Hey Amit | Medium
March 6, 2025 - When working with data in Python, you’ll often run into situations where the data type just isn’t what you need. Maybe a column is a string (object), but you need it as an integer. This is where pandas astype() steps in like a data wizard.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 35499
BUG: pandas 1.1.0 MemoryError using .astype("string") which worked using pandas 1.0.5 · Issue #35499 · pandas-dev/pandas
July 31, 2020 - MemoryError Traceback (most recent call last) <ipython-input-38-939f88862e64> in <module> ----> 1 df['event_html_body'].astype("string") /opt/conda/lib/python3.7/site-packages/pandas/core/generic.py in astype(self, dtype, copy, errors) 5535 else: 5536 # else, only a single dtype is given -> 5537 new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,) 5538 return self._constructor(new_data).__finalize__(self, method="astype") 5539 /opt/conda/lib/python3.7/site-packages/pandas/core/internals/managers.py in astype(self, dtype, copy, errors) 565 self, dtype, copy: bool = False, errors:
Author   ldacey
🌐
AskPython
askpython.com › home › python astype() – type conversion of data columns
Python astype() - Type Conversion of Data columns - AskPython
February 16, 2023 - Python astype() method enables us to set or convert the data type of an existing data column in a dataset or a data frame.
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › astype
Python Pandas DataFrame astype() - Change Data Type | Vultr Docs
December 24, 2024 - python Copy · import pandas as pd data = {'col1': [1, 2, 3], 'col2': ['4', '5', '6']} df = pd.DataFrame(data) df['col2'] = df['col2'].astype(int) print(df) Explain Code · This code converts the col2 from string type to integer type. The operation is performed in-place, directly modifying the data frame.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas dataframe.astype() – examples
Pandas DataFrame.astype() - Examples - Spark By {Examples}
July 7, 2025 - DataFrame.astype() function is used to cast a column data type (dtype) in pandas object, it supports String, flat, date, int, datetime any many other dtypes supported by Numpy.