Carola
Carola

Reputation: 366

Match dtypes of two DataFrames that share columns

I have the following dataframes in pandas:

df:
| ID       | country        | money     | code     | money_add | other |
| -------- | -------------- | --------- | -------- | --------- | ----- |
| 832932   | Other          | NaN       | 00000    |   NaN     | NaN   |
| 217#8#   | NaN            | NaN       | NaN      |   NaN     | NaN   |
| 1329T2   | France         | 12131     | 00020    |   3452    | 123   |
| 124932   | France         | NaN       | 00016    |   NaN     | NaN   |
| 194022   | France         | NaN       | 00000    |   NaN     | NaN   |
df1:

| cod_t    | money  | money_add | other |
| -------- | ------ | --------- | ----- |
| 00000    |  4532  | 72323     | 321   |
| 00016    |  1213  | 23822     | 843   |
| 00018    |  1313  | 8393      | 183   |
| 00020    |  1813  | 27328     | 128   |
| 00030    |  8932  | 3204      | 829   |
cols = df.columns.intersection(df1.columns)
print (df[cols].dtypes.eq(df1[cols].dtypes))
money        False
money_add    False
other        False
dtype: bool

I want to match the dtypes of the columns of the second dataframe to be equal to those of the first one. Is there any way to do this?

Upvotes: 1

Views: 517

Answers (1)

Khaled Koubaa
Khaled Koubaa

Reputation: 527

try:

for i in df1.columns.tolist():
    df1[f'{i}'] = df1[f'{i}'].astype(df[f'{i}'].dtype)

Upvotes: 2

Related Questions