Pandas astype()

The astype() method in Pandas is used to cast a pandas object to a specified data type.

Example

import pandas as pd

# sample DataFrame
data = {'A': ['1', '2', '3'],
        'B': ['4.5', '5.7', '6.8']}

df = pd.DataFrame(data)

# convert entire DataFrame to float
df = df.astype(float)

print(df)

'''
Output

     A    B
0  1.0  4.5
1  2.0  5.7
2  3.0  6.8
'''

astype() Syntax

The syntax of the astype() method in Pandas is:

df.astype(dtype, copy, errors)

astype() Argument

The astype() method takes the following argument:

  • dtype - data type or dictionary of column to data type to convert the dataframe into
  • copy - whether to return a copy
  • errors - controls raising exceptions on invalid data types

astype() Return Value

The astype() method returns a DataFrame with data cast to specified data types.


Example 1: Convert Entire DataFrame to a Single Data Type

import pandas as pd

# sample DataFrame
data = {'A': ['1', '2', '3'],
        'B': ['4.5', '5.7', '6.8']}

df = pd.DataFrame(data)

# convert entire DataFrame to float
df = df.astype(float)

print(df)

Output

     A    B
0  1.0  4.5
1  2.0  5.7
2  3.0  6.8

In this case, we converted the entire DataFrame df to have all its values as float values using the astype() method.


Example 2: Convert Data Type of Single Column

import pandas as pd

# sample DataFrame
data = {'A': ['1', '2', '3'],
        'B': ['4', '5', '6']}

df = pd.DataFrame(data)

# convert column B to float
converted_b = df['B'].astype(float)

print(converted_b)

Output

0    4.0
1    5.0
2    6.0
Name: B, dtype: float64

In this example, we converted the data type of column B. Notice how the astype() function only returns the converted column only.


Example 3: Convert Data Type of Multiple Columns

import pandas as pd

# sample DataFrame
data = {'A': ['1', '2', '3'],
        'B': ['4', '5', '6']}

df = pd.DataFrame(data)

# convert data types of columns A and B
df = df.astype({'A': int, 'B': float})

print(df)

Output

   A    B
0  1  4.0
1  2  5.0
2  3  6.0

In this example, we passed a dictionary in the format {col_name: dtype, ...} to the astype() method to convert data types of multiple columns.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community