Change language

Python | Pandas Series.astype () to convert Series Data Type

Pandas astype() — one of the most important methods. Used to change the data type of a series. When a data frame is created from a CSV file, the columns are imported and the data type is automatically set, which is often not the case. For example, a salary column can be imported as a string, but in order to perform operations, we must convert it to a float. 
astype() is used for such data type conversions.

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. ’raise’ will raise the error and ’ignore’ will pass without raising error.

Return type: Series with changed data types

To download the dataset used in the following example, click here.
In the following examples, the data frame used contains the data of some NBA players. An image of the data frame before any operations is attached below. 

Example:
In this example, the data frame is imported and .dtypes is called on the dataframe to view the data types of the series. After that, some columns are converted using the .astype () method and the dtypes are scanned again to see the changes.

# pandas module import

import pandas as pd

 
# read CSV file from URL

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# deleting null columns, to avoid errors

da ta.dropna (inplace = True )

 
# save dtype before conversion

before = data.dtypes

 
# converting dtypes using astype

data [ "Salary" ] = data [ "Salary" ]. astype ( int )

data [ "Number" ] = data [ "Number" ]. astype ( str )

  
# saving dtype after conversion

after = data.dtypes

 
# print for comparison

print ( "BEFORE CONVERSION" , before, "" )

print ( " AFTER CONVERSION " , after, " " )

Output:
As shown in the output image , the data types of the columns have been converted accordingly. in the usual way. 

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically