私は、あるDataFrameから別のものに変更されたレコードをチェックする必要があります。 すべての列に一致する必要があります。パンダで平等のチェックが遅すぎる
1つはExcelファイル(new_df
)、1つはSQLクエリ(sql_df
)です。形状は〜20,000行×39列です。
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
を取り、彼らと他のタスクを実行します。私は、これはdf.equals(other_df)
は現在、私は次のように使用していますのために良い仕事だと思いました。
これは私のパフォーマンス上の問題の原因である可能性がありますので避けることを望む多くのループがあります。現在、2万レコードで5分以上かかる(ハードウェアによって異なる)、これは性能が悪いことです。私は、すべての列を1つの長い文字列に追加/連結して比較することを考えていましたが、それは別の非効率的な方法のようです。これを解決するためのより良い方法は何でしょうか/空のリストソリューションにこのような不都合な追加を避けるにはどうすればよいですか?
「equals」とは何が原因だと思いますか? – user2357112
@ user2357112 - 有効なポイント。 *簡単にルーピングの量にすることができました - 私はこのことについてあまり誤解を与えないようにタイトルを更新しました – MattR
'new_df'と' sql_df'(または類似しているもの)の両方のサンプルは、実際の解決策を提供するのに大いに役立ちます。 – FabienP