0
0

More than 1 year has passed since last update.

【データ結合/Python】左外部結合でmergeすると、右側のテーブルの値がNaNで結合されてしまう

Posted at

今回の課題

train.csv(train_df)を左、tranaction.csv(transaction_df)を右側で左外部結合したところ、
transaction_dfのtransactionsカラムがNaNになってしまった。

原因としては、
結合するためのキーとして設定していたdateカラムが、
train_dfとtransaction_dfの間で一つも一致するものが無く、うまく結合ができていなかっただけ
だった...。

初歩的な原因ではあったが、
pythonでデータの結合を試行錯誤した記録としてメモに残すことにした。

※補足
Store Sales - Time Series Forecastingで配布されているCSVデータを少し加工して、結合しようとしました。

試行錯誤した内容

1)dateとstore_nbrをキーにして、左外部結合してみた

transaction_date_family_train_df = pd.merge(train_df, transaction_df, on=['date', 'store_nbr'], how='left')
transaction_date_family_train_df.head()

これだと、transaction_df側の、transactionsカラムがNaNってしまった。

2)dateとstore_nbrをキーにして、右側外部結合してみた

transaction_date_family_train_df = pd.merge(train_df, transaction_df, on=['date', 'store_nbr'], how='right')
transaction_date_family_train_df.head()

これだと、train_df側のsalesカラムとonpromotionカラムがNULLとなってしまった。

3)dateとstore_nbrをキーにして、内部結合してみた

transaction_date_family_train_df = pd.merge(train_df, transaction_df, on=['date', 'store_nbr'], how='inner')
transaction_date_family_train_df.head()

生成したデータフレームにはデータが何も格納されなかった。

上記のように試行錯誤した結果、
結合のキーに設定しているカラムに問題があるのではないか? と考えた。

そして、下記の2つを試してみた。

最後に試したこと

  • dateだけをキーにして内部結合
  • store_nbrだけをキーに内部結合

この2つを試してみると、
store_nbrだけをキーにして結合する場合は、データが抽出されるのに対して、
dateだけをキーにして結合すると、何もデータが抽出されなかった。

以上の結果から、
結合するためのキーとして設定していたdateカラムが、
train_dfとtransaction_dfの間で一つも一致するものが無く、うまく結合ができていなかっただけ
だったと言うことがわかった。

0
0
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
0
0