I am converting data types of dataframe df2 same as df1 by using below code but it is giving me this error.
code:
df2 = df2.astype(df1.dtypes.to_dict())
Error:
invalid literal for int() with base 10 error in pandas: "0.75" in pandas
Is there any general solution to fix this line of code?
I tried converting both the data frames values to string but didn't work.
df2.astype(str)
df2 = df2.astype(df1.astype(str).dtypes.to_dict())
CodePudding user response:
0.75 is not an integer. Therefore it breaks.
If you want to transform 0.75 to 1 you can round the values and then transform then to integers.
But I guess you should firstly check if thats really what you want to do
CodePudding user response:
I don't know exact situation of your dataset because there is no example.
try this one
cols = df1.select_dtypes('number').columns
df2[cols] = df2[cols].apply(pd.to_numeric, errors='coerce')
df2 = df2.astype(df1.dtypes)
CodePudding user response:
This one might be perfect if you just wanna mirror data type of every column in df1 to df2.
for x in df1.columns:
df2[x]=df2[x].astype(df1[x].dtypes.name)