2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】DataFrame 横方向の結合方法3種類 比較まとめ

Posted at

DataFrame 横方向の結合方法3種類 比較まとめ

import pandas as pd

df1 = pd.DataFrame({'A': ['A1', 'A2', 'A3'],
                    'B': ['B1', 'B2', 'B3'],
                    'C': ['C1', 'C2', 'C3']},
                   index=['ONE', 'TWO', 'THREE'])

df2 = pd.DataFrame({'C': ['C2', 'C3', 'C4'],
                    'D': ['D2', 'D3', 'D4']},
                   index=['TWO', 'THREE', 'FOUR'])

display(df1)
display(df2)
A B C
ONE A1 B1 C1
TWO A2 B2 C2
THREE A3 B3 C3

C D
TWO C2 D2
THREE C3 D3
FOUR C4 D4

1. pd.concat()

result = pd.concat([df1, df2], axis=1)
print(result)
A B C C D
ONE A1 B1 C1 NaN NaN
TWO A2 B2 C2 C2 D2
THREE A3 B3 C3 C3 D3
FOUR NaN NaN NaN C4 D4

複数のDataFrameを単純に縦または横方向に結合するために使用されます。
横方向に結合する際はインデックスを参照します。
また、3つ以上のDataFrameを同時に結合することも可能です。

2. pd.DataFrame.merge()

result = df1.merge(df2, on='C')
print(result)
A B C D
0 A2 B2 C2 D2
1 A3 B3 C3 D3

特定のカラムをもとに2つのDataFrameを結合します。
条件を細かく指定することで、SQLのようなJOIN操作を行うことが可能です。

3. pd.DataFrame.join()

result = df1.join(df2, lsuffix='_l', rsuffix='_r')
print(result)
A B C_l C_r D
ONE A1 B1 C1 NaN NaN
TWO A2 B2 C2 C2 D2
THREE A3 B3 C3 C3 D3

merge()と似ていますが、こちらはインデックスをもとにDataFrameを結合します。
結合によりカラム名が重複する場合はサフィックスを指定する必要があります。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?