Cody
Cody

Reputation: 499

Convert data types of a Pandas dataframe to match another

I have two data frames with the same column names but different data types:

df1.dtypes

order                                                                                                             
int64
x                                                                                                                                
int64
y                                                                                                                     
int64

df2.dtypes

order                                                                                                            
object
x                                                                                                                    
object
y                                                                                                                    
object

The dataframes are much larger than this, so I would like to capture the names/dtypes of df1 and convert df2 to match.

Upvotes: 26

Views: 19039

Answers (2)

Pete C
Pete C

Reputation: 609

The short version:

df2 = df2.astype(df1.dtypes.to_dict())

Upvotes: 44

BENY
BENY

Reputation: 323226

dtypes + name and using astype convert

df=pd.DataFrame({'title':list('ABC'),'TestData':['Test1(data)','t(data2)','Ts(data 3)'],'Value':[1,2,3]})
df1=pd.DataFrame({'title':list('ABC'),'TestData':['Test1(data)','t(data2)','Ts(data 3)'],'Value':['1','2','3']})

df.dtypes
Out[287]:
TestData    object
Value        int64
title       object
dtype: object
df1.dtypes
Out[288]:
TestData    object
Value       object
title       object
dtype: object

for x in df1.columns:
    df[x]=df[x].astype(df1[x].dtypes.name)
df.dtypes
Out[290]: 
TestData    object
Value       object
title       object
dtype: object

Upvotes: 18

Related Questions