Convert String Column to Integer in pandas DataFrame in Python (3 Examples)

This tutorial illustrates how to transform a column from string to integer in Python programming.

Setting up the Examples

import pandas as pd                                  # Load pandas library
df = pd.DataFrame({'A':['15', '2', '12', '9', '7'],  # Constructing a pandas DataFrame
                   'B':['10', '21', '4', '15', '25'],
                   'C':['35', '4', '51', '77', '8']})
print(df)
#     A   B   C
# 0  15  10  35
# 1   2  21   4
# 2  12   4  51
# 3   9  15  77
# 4   7  25   8
print(df.dtypes)                                     # Printing the data types of all columns
# A    object
# B    object
# C    object
# dtype: object

Example 1: Transforming One Column of a pandas DataFrame from String to Integer

df1 = df.copy()                                      # Duplicate pandas DataFrame
df1['A'] = df1['A'].astype(int)                      # Converting string to integer
print(df1.dtypes)                                    # Printing the data types of all columns
# A     int32
# B    object
# C    object
# dtype: object

Example 2: Transforming Multiple Columns of a pandas DataFrame from String to Integer

df2 = df.copy()                                      # Duplicate pandas DataFrame
df2 = df2.astype({'A': int, 'C': int})               # Converting string to integer
print(df2.dtypes)                                    # Printing the data types of all columns
# A     int32
# B    object
# C     int32
# dtype: object

Example 3: Transforming Each Column of a pandas DataFrame from String to Integer

df3 = df.copy()                                      # Duplicate pandas DataFrame
df3 = df3.astype(int)                                # Converting string to integer
print(df3.dtypes)                                    # Printing the data types of all columns
# A    int32
# B    int32
# C    int32
# dtype: object

Further Resources & Related Tutorials

Have a look at the following Python programming tutorials. They illustrate topics such as character strings and naming data:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top