Convert Integer Column to String Data Type in pandas DataFrame in Python (3 Examples)
In this Python programming tutorial you’ll learn how to convert an integer column to the string data type in a pandas DataFrame.
Introduction of Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
df = pd.DataFrame({'A':[7, 2, 12, 9, 7], # Constructing a pandas DataFrame 'B':[10, 9, 4, 22, 25], 'C':[35, 4, 42, 7, 13]}) print(df) # A B C # 0 7 10 35 # 1 2 9 4 # 2 12 4 42 # 3 9 22 7 # 4 7 25 13 |
df = pd.DataFrame({'A':[7, 2, 12, 9, 7], # Constructing a pandas DataFrame 'B':[10, 9, 4, 22, 25], 'C':[35, 4, 42, 7, 13]}) print(df) # A B C # 0 7 10 35 # 1 2 9 4 # 2 12 4 42 # 3 9 22 7 # 4 7 25 13
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object |
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object
Example 1: Transforming One Column of a pandas DataFrame from Integer to String
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(str) # Converting integer to string |
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(str) # Converting integer to string
print(df1.dtypes) # Printing the data types of all columns # A object # B int64 # C int64 # dtype: object |
print(df1.dtypes) # Printing the data types of all columns # A object # B int64 # C int64 # dtype: object
Example 2: Transforming Multiple Columns of a pandas DataFrame from Integer to String
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': str, 'C': str}) # Converting integer to string |
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': str, 'C': str}) # Converting integer to string
print(df2.dtypes) # Printing the data types of all columns # A object # B int64 # C object # dtype: object |
print(df2.dtypes) # Printing the data types of all columns # A object # B int64 # C object # dtype: object
Example 3: Transforming Each Column of a pandas DataFrame from Integer to String
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(str) # Converting integer to string |
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(str) # Converting integer to string
print(df3.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object |
print(df3.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object
Further Resources & Related Tutorials
Furthermore, you might want to have a look at the related Python articles on my homepage: