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
python - pandas astype(): str vs 'string' vs StringDtype - Stack Overflow
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.... More on stackoverflow.com
🌐 stackoverflow.com
Unable to convert a pandas object to a string in my DataFrame
object is just the dtype pandas uses for columns that contain values of type str (and many other Python types). The actual values themselves are still strings: import pandas as pd df = pd.DataFrame([["hello"], ["world"]], columns=["words"]) df.dtypes >>> words object dtype: object type(df.loc[0, "words"]) >>> Using .astype(str) does convert all values to string if they aren't already, but it doesn't change the column dtype by design. The only way around this is to use pandas's own string type via .astype("string"), but that's different from the str type, obviously. What exactly are the issues you are facing with the API? More on reddit.com
🌐 r/learnpython
6
3
December 10, 2021
🌐
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.
🌐
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
🌐
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 ...
🌐
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, ...
🌐
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'.
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.
🌐
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 - You can convert a specific column to a string type while keeping other columns as they are. For example, to convert 'Fee' to a string and leave the rest of the DataFrame unchanged.
🌐
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
🌐
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
🌐
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
🌐
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.
🌐
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.
🌐
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.
🌐
Reddit
reddit.com › r/learnpython › unable to convert a pandas object to a string in my dataframe
r/learnpython on Reddit: Unable to convert a pandas object to a string in my DataFrame
December 10, 2021 -

Trying to use the YouTube API to pull through some videos for data analysis and am currently using just two videos in a dataframe to play around with the functionality as I'm new to all of this.

I'm using another API to get the transcripts for each video but I need to input the video_id into that API to get transcripts for each video.

The only problem is everything is stored as an object and whenever I try .astype(str) or something like that, it still says the data is an object and means I can't do anything with the data when a string is a required argument for the other API

This is what I get when calling .info() on my dataframe:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 10 columns):
 #   Column                Non-Null Count  Dtype 
---  ------                --------------  ----- 
 0   video_id              2 non-null      object
 1   publishedAt           2 non-null      object
 2   channelId             2 non-null      object
 3   title                 2 non-null      object
 4   description           2 non-null      object
 5   channelTitle          2 non-null      object
 6   tags                  2 non-null      object
 7   categoryId            2 non-null      object
 8   liveBroadcastContent  2 non-null      object
 9   defaultAudioLanguage  2 non-null      object
dtypes: object(10)
memory usage: 288.0+ bytes

Any help would be really appreciated or an explanation of how these issues are usually handled