はじめに
前回は merge について軽くまとめたので今回は concat を見てみる
concat は連結という意味なので、電車が連結するかのように別々のものがくっついて統合されないイメージがあります。
ベースデータ準備
import numpy as np import pandas as pd df1 = pd.DataFrame(np.random.randn(3,3), columns=['D', 'C', 'A']) df2 = pd.DataFrame(np.random.randn(4,3), columns=['A', 'B', 'C'])

concat
- 何も指定していない場合のオプション
sort = Trueaxis = 0
コード
pd.concat([df1, df2])
結果

df1が上にあり、下にdf2のデータがあることがわかる- 列の整列について注意が表示される
FutureWarning: Sorting because non-concatenation axis is not aligned. A future version
of pandas will change to not sort by default.To accept the future behavior, pass ‘sort=False’.
To retain the current behavior and silence the warning, pass ‘sort=True’.
もともと df1の列が DCA の順番だったのが ABCD に並び替わっている。
未来のバージョンではソートしないよと書いてある。その挙動にするいは sort=False という引数を与えてくれと言っている。
コード2(sort=False)
pd.concat([df1, df2], sort=False)
結果

- 列の並び順が変わっていないことが確認できる。
concat ignore_index
- 既存のインデックスを無視して、再度振り直す
コード
pd.concat([df1, df2], ignore_index=True)
結果

- index がもともとの
0120123だったのが0123456となっていることがわかる
最後に
join などを使えば、結合方法も指定できるみたいだけど、この辺がmergeとごっちゃになる原因かも。
ということで merge でできそうな事は merge でやるとして。concat と分けて覚えておかなければ。


