pandas:How to bulk convert data type of dataframe columns

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I made a note, how to bulk convert data type of dataframe columns by for loop, when working with pandas dataframes.
I am writing a sample code, 'Convert all columns data type' pattern, and 'Convert columns data type except for some columns'
These sample code are usefull, when you handle a lot of dataframe columns.

Convert all columns data type

import pandas as pd

# Sample data
sample_list = {'sampleA':[1,2,3],
               'sampleB':[4,5,6]}

# Create dataframe
df = pd.DataFrame(sample_list)
print(df)
"""
   sampleA  sampleB
0        1        4
1        2        5
2        3        6
"""

# loop dataframe columns
for i in df.columns:
	df[f'{i}'] = df[f'{i}'].astype(float)

print(df)
"""
   sampleA  sampleB
0      1.0      4.0
1      2.0      5.0
2      3.0      6.0
"""

Convert columns data type except for some columns

import pandas as pd

# Sample data
sample_list = {'sampleA':[1,2,3],
               'sampleB':[4,5,6],
               'sampleC':['A','B','C']}

# Create dataframe
df = pd.DataFrame(sample_list)
print(df)
"""
   sampleA  sampleB sampleC
0        1        4       A
1        2        5       B
2        3        6       C
"""

# exclude list of columns name
exclude_list = ['sampleC']

# loop dataframe columns, but exclude if columns name are in the exclude_list
for i in df.columns:
	if i not in exclude_list:
		df[f'{i}'] = df[f'{i}'].astype(float)

print(df)
"""
   sampleA  sampleB sampleC
0      1.0      4.0       A
1      2.0      5.0       B
2      3.0      6.0       C
"""
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.