2
1

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.

Pandasのlocの仕様が変わったのでメモ

Posted at
data = [[1,2,3],[4,5,6],[7,8,9]]
col = ['A','C','E']
df = pd.DataFrame(data, columns=col)
#   A  C  E
# 0  1  2  3
# 1  4  5  6
# 2  7  8  9

Pandas 0.23以前ではこれに対してlocで項目にA,B,Cと指定すると
データにない項目名はすべて欠損値として作成されていた。

sel_col = ['A','B','C']
print(df.loc[:,sel_col])
# version 0.23以前の場合
#   A   B  C
# 0  1 NaN  2
# 1  4 NaN  5
# 2  7 NaN  8

しかしPandas 1.0以降では以下のようなエラーが出るようになった。
image.png

どうやらデータフレームにない項目を指定してはいけないことになったらしい。
以前と同じようにデータフレームにない項目は欠損として作りたい場合は代わりにreindexを使えば可能だ。

sel_col = ['A','B','C']
print(df.reindex(columns=sel_col))
#   A   B  C
# 0  1 NaN  2
# 1  4 NaN  5
# 2  7 NaN  8

もしくはデータフレームに含まれる項目のみを表示させたい場合は以下のように
データフレームの項目と指定項目のintersectionをとることができるらしい。

print(df.loc[:,df.columns.intersection(sel_col)])
#   A  C
# 0  1  2
# 1  4  5
# 2  7  8
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?