I have a dataframe that has 3 columns and looks like this:
JavaScript
x
4
1
name date result
2
Anya 2021-02-13 0
3
Frank 2021-02-14 1
4
The other dataframe looks like this:
JavaScript
1
4
1
name date
2
Anya 2021-02-13
3
Frank 2021-02-14
4
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
1
19
19
1
df_1.info()
2
Data columns (total 3 columns):
3
# Column Non-Null Count Dtype
4
--- ------ -------------- -----
5
0 name 717 non-null object
6
1 date 717 non-null object
7
2 result 717 non-null int64
8
9
df_2.info()
10
Data columns (total 3 columns):
11
# Column Non-Null Count Dtype
12
--- ------ -------------- -----
13
0 name 717 non-null object
14
1 date 717 non-null datetime64[ns]
15
16
# Match the primary df to secondary df
17
for x in df_1.columns:
18
df_2[x] = df_2[x].astype(df_1[x].dtypes.name)
19
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
1
3
1
df1->that has 3 columns
2
df2->other dataframe
3
Firstly make use of boolean mask to find out those columns which are common in both dataframes:
JavaScript
1
3
1
mask=df1.columns.isin(df2.columns)
2
df=df1[df1.columns[mask]]
3
Now finally make use of astype()
method:
JavaScript
1
2
1
df2=df2.astype(df.dtypes)
2
Or you can do all this in 1 line by:
JavaScript
1
2
1
df2=df2.astype(df1[df1.columns[df1.columns.isin(df2.columns)]].dtypes)
2