Skip to content
Advertisement

match dtypes of one df to another with different number of columns

I have a dataframe that has 3 columns and looks like this:

JavaScript

The other dataframe looks like this:

JavaScript

I need to match the data types of one df to another. Because I have one additional column in df_1 I got an error. My code looks like this:

JavaScript

I got an error: KeyError: 'profitable' What would be a workaround here? I need the dtypes of df_2 to be exactly the same as df_1. Thanks!

Advertisement

Answer

JavaScript

Firstly make use of boolean mask to find out those columns which are common in both dataframes:

JavaScript

Now finally make use of astype() method:

JavaScript

Or you can do all this in 1 line by:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement