Minifycode 2021-10-03 Viewed 1.4K times Artificial Intelligence (AI)

In this article, you will learn how to Change Data Type for one or more columns in Pandas Dataframe

 

In this article, you will learn how to changing Data Type for one or more columns in Pandas Dataframe.

 

import pandas as uc

d = uc.DataFrame({ 
	'A': [1, 2, 3, 4, 5, 6], 
	'B': ['a', 'b', 'c', 'd', 'e', 'f'], 
	'C': [1.1, '1.0', '1.3', 2, 5, 10] }) 

# converting all columns to string type 
d = d.astype(str) 
print(d.dtypes) 

 

Change data type of a specific column of a pandas DataFrame


Pandas will always store strings as objects.


Alter column data type from Int64 to String.

import pandas as pd
 
df = pd.DataFrame({'Age': [30, 20, 22, 40, 32, 28, 39],
                   'Color': ['Blue', 'Green', 'Red', 'White', 'Gray', 'Black',
                             'Red'],
                   'Food': ['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese',
                            'Melon', 'Beans'],
                   'Height': [165, 70, 120, 80, 180, 172, 150],
                   'Score': [4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
                   'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
                         'Christina', 'Cornelia'])
 
print(df.dtypes)
 
df['Age'] = df['Age'].astype(str)
 
print(df.dtypes)

 

C:\python\pandas examples>python example.py
Age         int64
Color      object
Food       object
Height      int64
Score     float64
State      object
dtype: object
Age        object
Color      object
Food       object
Height      int64
Score     float64
State      object
dtype: object
 
C:\python\pandas examples>

Change Data Type for one or more columns in Pandas Dataframe
minify code