Convert Column Data Types in Pandas Python

preview_player
Показать описание
This recipe demonstrates how convert columns data types in pandas.

#python​ #recipes​ #dataanalytics​ #datascience​ #pandas​ #dataframe​

How do i convert data types in Pandas in Python?

Welcome to techminded python recipes in this recipe we will show you how to convert data types in a pandas data frame

In the real world data rarely ever comes in a nice and clean format just waiting for you to manipulate it. Instead, quite often data when collected is very messy.

One of the many challenges you may encounter during data ingestion is the fact that the data types may be incorrect or mixed. Some other times you want to convert the data intentionally to another data type. There are also the times when functions and operations change the data type of the data.

In this recipe we will show you how to convert data types single columns as well as to entire data frames.

00:23​ Introduction
01:24​ Create Sample Data with integers Frame and Sorting
02:13​ Replacing Some elements to integers prevents sorting
02:55​ Changing type of single columns
03:25​ Changing Type of entire data frames
03:50​ Changing type of multiple pandas data frame columns using slicing

#######################################################
CODE
#######################################################

##type​ conversion in Pandas
import pandas as pd

df = pd.DataFrame([[1,1,1],
[2,2,2],
[3,3,3],
[4,4,4]],
columns = ['col_1', 'col_2', 'col_3'])

df

df = pd.DataFrame([[1,1,1],
[2,2,2],
['3',3,3],
[4,4,4]],
columns = ['col_1', 'col_2', 'col_3'])

df['col_1']=df['col_1'].astype('int64')

df = pd.DataFrame([['1','1','1'],
['2','2','2'],
[ 3 ,'3','3'],
['4','4','4']],
columns = ['col_1', 'col_2', 'col_3'])

df

df['col_1']=df['col_1'].astype('str')

df

Рекомендации по теме