はじめに
最近データ分析をやっと実践で勉強するようになり、Pandasをまったく使いこなせないなと実感するようになりました。
今回はそんなPandasでよく使うmergeにまつわ問題とその解決策をまとめました。
今後DataFrameの操作について記事をたくさん載せていく予定です。
問題
まず以下の二つのDataFrameを用意します。
df_a
| index | No |
|---|---|
| 11 | one |
| 12 | two |
| 13 | three |
df_b
| index | No | Value |
|---|---|---|
| 0 | one | 1 |
| 1 | two | 2 |
| 2 | three | 3 |
そして、この二つをNoでマージします。
a = ["one", "two", "three"]
a_df = pd.DataFrame(a, index=['11','12', '13'], columns=["No"])
b = ["one", "two", "three"]
value = ["1", "2", "3"]
b_df = pd.DataFrame(b, index=['1', '2', '3'], columns=["No"])
b_df["value"] = value
result = pd.merge(a_df, b_df, on="No")
print(result)
すると以下のDataFrameが作成されます。
result
| index | No | Value |
|---|---|---|
| 0 | one | 1 |
| 1 | two | 2 |
| 2 | three | 3 |
しかし本来は、このようなDataFrameが作りたいと考えていました。
| index | No | Value |
|---|---|---|
| 11 | one | 1 |
| 12 | two | 2 |
| 13 | three | 3 |
indexが11-13にしたいのですが、0-2と振りなおされています。
解決方法
1行でうまく解決できないかとteratailで質問したところ以下の方法で可能とわかりました。
result = pd.merge(a_df.reset_index(), b_df, on="No").set_index('index')
まず、a_dfをreset_indexで0-2を振りなおします。
| index | index | No |
|---|---|---|
| 0 | 11 | one |
| 1 | 12 | two |
| 2 | 13 | three |
するとindexカラムが追加されます。
そして、mergeします。
| index | index | No | Value |
|---|---|---|---|
| 0 | 11 | one | 1 |
| 1 | 12 | two | 2 |
| 2 | 13 | three | 3 |
そのあと、11-13のindexカラムをset_index()でindexにします。
| index | No | Value |
|---|---|---|
| 11 | one | 1 |
| 12 | two | 2 |
| 13 | three | 3 |
おわりに
全然技術がないことを実感しました。
毎日努力して少しでも早くなれるようがんばります。
DataFrameの操作は詰まったら記事に上げるようにします。