5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pd.concat(df,axis=0)で列の順番が勝手に変わる!?

Last updated at Posted at 2019-10-15

注意

本記事は2019年10月15日におけるKaggle Notebook上で実験したものです。
2021年4月7日におけるKaggle Notebookでは下記の現象は起きなかったため、バージョンが上がり改善されたと思われます。
pd.concat()の引数sortのデフォルトがFalseになっているようです。

何があったの

pd.concat()にて縦方向の結合を行ったら、列の順番が勝手に変わる事象に出くわしたため、
その解決法を書きます。

問題

タイタニックデータをインポートして

import pandas as pd
train = pd.read_csv('../input/titanic/train.csv')
test = pd.read_csv('../input/titanic/test.csv')

trainとtestを見てみると

image.png

これをconcatを用いて縦方向に結合すると
image.png

列がアルファベット順に入れ替わります。

解決法

sort=Falseを追記してあげれば解決します。

train_test_concat = pd.concat([train,test],axis=0,sort=False)

結果
image.png

warningを見れば一発ですが、
下記のコードのようにwarningを無視していると意外とはまるため、
一応記事にまとめました。

import warnings
warnings.simplefilter('ignore')
5
4
1

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?