我有一个检查从一个DataFrame更改为另一个的记录的要求。它必须匹配全部列。大熊猫检查平等太慢使用
一个是excel文件(new_df
),一个是SQL查询(sql_df
)。形状是〜20,000行×39列。我认为这将是df.equals(other_df)
目前我使用下面的工作:
import pandas as pd
import numpy as np
new_df = pd.DataFrame({'ID' : [0 ,1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : [1,0,3,5,0,0,np.NaN,9,0,0],
'C' : [10,0,30,50,0,0,4,10,1,3],
'D' : [1,0,3,4,0,0,7,8,0,1],
'E' : ['Universtiy of New York','New Hampshire University','JMU','Oklahoma State','Penn State',
'New Mexico Univ','Rutgers','Indiana State','JMU','University of South Carolina']})
sql_df= pd.DataFrame({'ID' : [0 ,1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : [1,0,3,5,0,0,np.NaN,9,0,0],
'C' : [10,0,30,50,0,0,4,10,1,0],
'D' : [5,0,3,4,0,0,7,8,0,1],
'E' : ['Universtiy of New York','New Hampshire University','NYU','Oklahoma State','Penn State',
'New Mexico Univ','Rutgers','Indiana State','NYU','University of South Carolina']})
# creates an empty list to append to
differences = []
# for all the IDs in the dataframe that should not change check if this record is the same in the database
# must use reset_index() so the equals() will work as I expect it to
# if it is not the same, append to a list which has the Aspn ID that is failing, along with the columns that changed
for unique_id in new_df['ID'].tolist():
# get the id from the list, and filter both sql and new dfs to this record
if new_df.loc[new_df['ID'] == unique_id].reset_index(drop=True).equals(sql_df.loc[sql_df['ID'] == unique_id].reset_index(drop=True)) is False:
bad_columns = []
for column in new_df.columns.tolist():
# if not the same above, check which column using the same logic
if new_df.loc[new_df['ID'] == unique_id][column].reset_index(drop=True).equals(sql_df.loc[sql_df['ID'] == unique_id][column].reset_index(drop=True)) is False:
bad_columns.append(column)
differences.append([unique_id, bad_columns])
后来我拿differences
和bad_columns
和执行其它任务与他们。
有很多循环,我希望避免...因为这可能是我的性能问题的原因。目前,20,000个记录需要5分钟以上(硬件上有所不同),这是糟糕的表现。我想加入/连接所有列成一个长字符串来比较,但这似乎是另一种低效率的方式。解决这个问题的更好方法是什么?我怎样才能避免将这种混乱添加到空列表解决方案中?
是什么让你觉得'等于'是罪魁祸首? – user2357112
@ user2357112 - 有效点。 *很容易*是循环的数量 - 我更新了标题以减少误导这个 – MattR
来自'new_df'和'sql_df'的一个示例(或者看起来相似的东西)将极大地帮助提供工作解决方案。 – FabienP