Pandas read_sql 数据类型

Mat*_*ttR 6 python type-conversion dataframe pandas

我必须比较两个数据源,看看所有行中的同一记录是否相同。一个数据源来自 Excel 文件,另一个数据源来自 SQL 表。我尝试DataFrame.equals()像过去一样使用。

然而,该问题是由于讨厌的数据类型问题造成的。尽管数据看起来相同,但数据类型正在excel_df.loc[excel_df['ID'] = 1].equals(sql_df.loc[sql_df['ID'] = 1])返回False。以下是来自 的数据类型的示例pd.read_excel()

COLUMN ID                         int64
ANOTHER Id                      float64
SOME Date                datetime64[ns]
Another Date             datetime64[ns] 
Run Code Online (Sandbox Code Playgroud)

相同的列来自pd.read_sql

COLUMN ID                        float64
ANOTHER Id                       float64
SOME Date                         object
Another Date                      object
Run Code Online (Sandbox Code Playgroud)

我可以尝试使用convertersfrom 的参数pd.read_excel()来匹配 SQL。或者也在做df['Column_Name] = df['Column_Name].astype(dtype_here)但是我正在处理很多专栏。有没有更简单的方法来检查所有列的值?

检查pd.read_sql()没有类似的东西converters,但我正在寻找类似的东西:

df = pd.read_sql("Select * From Foo", con, dtypes = ({Column_name: str,
                                                      Column_name2:int}))
Run Code Online (Sandbox Code Playgroud)

Igo*_*ush 3

怎么样

excel_df = pd.read_excel(...)
sql_df = pd.read_sql(...)

# attempt to cast all columns of excel_df to the types of sql_df
excel_df.astype(sql_df.dtypes.to_dict()).equals(sql_df)
Run Code Online (Sandbox Code Playgroud)