JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame.astype() Function

Author:JIYIK Last Updated:2025/05/01 Views:

Python Pandas DataFrame.astype() function changes the data type of an object to the specified data type.


pandas.DataFrame.astype()grammar

DataFrame.astype(dtype, copy=True, errors="raise")

parameter

dtype The data type we want to assign to the object.
copy Boolean parameter. TrueReturns a copy when .
errors It controls the raising of exceptions on invalid data of the provided data type. It has two options. raise: Allow exceptions to be raised. ignore: Suppress exceptions. If there is an error then it will return the original object.

Return Object

It returns a DataFrame with the data type.


Example code: DataFrame.astype()Method to change a column data type

import pandas as pd

dataframe=pd.DataFrame({'Attendance': {0: 60, 1: 100, 2: 80,3: 78,4: 95},
                        'Name': {0: 'Olivia', 1: 'John', 2: 'Laura',3: 'Ben',4: 'Kevin'},
                        'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}})

print("The Original Data Types of the Data frame are: \n")
print(dataframe.dtypes)

dataframe1 = dataframe.astype({'Attendance': 'int32'}).dtypes
print("The Modified Data Types of the Data frame are: \n")
print(dataframe1)

Output:

The Original Data Types of the Data frame are: 

Attendance         int64
Name              object
Obtained Marks     int64
dtype: object
The Modified Data Types of the Data frame are: 

Attendance         int32
Name              object
Obtained Marks     int64
dtype: object

The function returns the converted data type. We use dtypes()the function to display the data type of each column in the DataFrame.


Example Code: DataFrame.astype()Method to change the data type of all columns in a DataFrame

We will try to change the data type of the given DataFrame.

import pandas as pd
dataframe=pd.DataFrame({'Attendance': {0: 60, 1: 100, 2: 80,3: 78,4: 95},
                        'Name': {0: 'Olivia', 1: 'John', 2: 'Laura',3: 'Ben',4: 'Kevin'},
                        'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}})
print("The Original Data Types of the Data frame are: \n")
print(dataframe.dtypes)

dataframe1 = dataframe.astype('object').dtypes
print("The Modified Data Types of the Data frame are: \n")
print(dataframe1)

Output:

The Original Data Types of the Data frame are: 

Attendance         int64
Name              object
Obtained Marks     int64
dtype: object
The Modified Data Types of the Data frame are: 

Attendance        object
Name              object
Obtained Marks    object
dtype: object

The function returns the modified DataFrame, which has changed the data types of all columns to object.


Sample code: DataFrame.astype()Exceptions when a method changes data type

Now we objectset the data type to int32. The function will ignore the exception because we will pass the parameter errors= 'ignore'.

import pandas as pd

dataframe=pd.DataFrame({'Attendance': {0: 60, 1: 100, 2: 80,3: 78,4: 95},
                        'Name': {0: 'Olivia', 1: 'John', 2: 'Laura',3: 'Ben',4: 'Kevin'},
                        'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}})

print("The Original Data Types of the Data frame are: \n")
print(dataframe.dtypes)

dataframe1 = dataframe.astype('int32', errors='ignore').dtypes
print("The Modified Data Types of the Data frame are: \n")
print(dataframe1)

Output:

The Original Data Types of the Data frame are: 

Attendance         int64
Name              object
Obtained Marks     int64
dtype: object
The Modified Data Types of the Data frame are: 

Attendance         int32
Name              object
Obtained Marks     int32
dtype: object

Notice that the function did not raise any exceptions. It ignored the error because we objectconverted to int32. It just did not change Namethe data type of the column.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Pandas DataFrame DataFrame.query() function

Publish Date:2025/04/30 Views:108 Category:Python

The pandas.DataFrame.query() method filters the rows of the caller DataFrame using the given query expression. pandas.DataFrame.query() grammar DataFrame . query(expr, inplace = False , ** kwargs) parameter expr Filter rows based on query e

Pandas DataFrame DataFrame.min() function

Publish Date:2025/04/30 Views:162 Category:Python

Python Pandas DataFrame.min() function gets the minimum value of the DataFrame object along the specified axis. pandas.DataFrame.min() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = None , ** kwargs) pa

Pandas DataFrame DataFrame.mean() function

Publish Date:2025/04/30 Views:86 Category:Python

Python Pandas DataFrame.mean() function calculates the mean of the values ​​of the DataFrame object over the specified axis. pandas.DataFrame.mean() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = No

Pandas DataFrame DataFrame.isin() function

Publish Date:2025/04/30 Views:133 Category:Python

The pandas.DataFrame.isin(values) function checks whether each element in the caller DataFrame contains values the value specified in the input . pandas.DataFrame.isin(values) grammar DataFrame . isin(values) parameter values iterable - lis

Pandas DataFrame DataFrame.groupby() function

Publish Date:2025/04/30 Views:161 Category:Python

pandas.DataFrame.groupby() takes a DataFrame as input and divides the DataFrame into groups based on a given criterion. We can use groupby() the method to easily process large datasets. pandas.DataFrame.groupby() grammar DataFrame . groupby

Pandas DataFrame DataFrame.fillna() function

Publish Date:2025/04/30 Views:61 Category:Python

The pandas.DataFrame.fillna() function replaces the values DataFrame ​​in NaN with a certain value. pandas.DataFrame.fillna() grammar DataFrame . fillna( value = None , method = None , axis = None , inplace = False , limit = None , down

Pandas DataFrame DataFrame.dropna() function

Publish Date:2025/04/30 Views:182 Category:Python

The pandas.DataFrame.dropna() function removes null values ​​(missing values) from a DataFrame by dropping rows or columns that contain null values DataFrame . NaN ( Not a Number ) and NaT ( Not a Time ) represent null values. DataFrame

Pandas DataFrame DataFrame.assign() function

Publish Date:2025/04/30 Views:55 Category:Python

Python Pandas DataFrame.assign() function assigns new columns to DataFrame . pandas.DataFrame.assign() grammar DataFrame . assign( ** kwargs) parameter **kwargs Keyword arguments, DataFrame the column names to be assigned to are passed as k

Pandas DataFrame DataFrame.transform() function

Publish Date:2025/04/30 Views:120 Category:Python

Python Pandas DataFrame.transform() DataFrame applies a function on and transforms DataFrame . The function to be applied is passed as an argument to the function. The axis length of transform() the transformed should be the same as the ori

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial