LoginSignup
7
1

pandasを使って、2つのTBLの差分を比較する (mergeを使って)

Posted at

やりたいこと

pythonのライブラリであるpandasを使って、
2つのTBLの差分を比較して相違点を洗い出したい。

コード

## csv読み込み
a1 = pd.read_csv("test.csv")
a2 = pd.read_csv("test2.csv")
## a1とa2をマージさせる
a_merge = pd.merge(a1,a2,how="outer",on="カラム1",indicator=True)
## value_countsでそれぞれの数を数える
a_merge["_merge"].values_counts()

概要

ここでの肝はindicatorを使うこと。
使うことにより、_mergeカラムができるのが大事。
このindicatorはleftやouterなどの結合で、どれぐらい紐づいているかを判別するオプションみたいですね。
試しに2つをマージして、_mergeをみてみます。
both,left_only,right_only3つの表示が出てきます。
これにより左にしかないもの、右にしかないものを見ることが可能になります!
最終的に、以下を実行すれば違うところが目に見えてわかるので便利かもしれにゃい。

a_merge[a_merge["_merge"] == "left_only"]
a_merge[a_merge["_merge"] == "right_only"]
## left_onlyはは左にしかないものを出してくれる。right_onlyは右
## このため、2つの相違点が洗い出すことができる。

参考:
https://qiita.com/mk_GF/items/2c47dfed15520d34f7d4

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1