0
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 5 years have passed since last update.

Pandasでバージョンにより微妙に異なる動作

Last updated at Posted at 2020-06-26

はじめに

Pandasは超便利なライブラリではあるが、バージョンが変わると、以前動作していたものが動作しなくなったりすることがある。今回は、0.24⇒1.0にした時のケースとして2点あげる。

その① ixが使えねー。

まずは、0.24で。'a'と'b'という列からなるデータフレームを作成し、ixで列を指定してみよう。

0.24
>>>a = pd.DataFrame([[1,2],[3,4]], index=[1,2], columns=['a', 'b'])
>>> a.ix[:, ['a','b']]
   a  b
1  1  2
2  3  4

普通に使える。
次に、1.0で。

1.0
>>> a.ix[:, ['a','b']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\generic.py", l

ine 5273, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'ix'

使えねー。
しかし焦ることはない。
ixの代わりにlocを使えばいいのだ。

その② locで存在しない列を指定するとエラー。

今度はそのまま、'c'という存在しない列を指定してみよう。
0.24の場合。

0.24
>>> a.loc[:, ['a','c']]
   a   c
1  1 NaN
2  3 NaN

列を自動的に作成し、'NaN'で埋めてくれるようだ。気が利きすぎ?

次1.0で。

1.0
>>> a.loc[:, ['a','c']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1760, in __getitem__
    return self._getitem_tuple(key)
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1287, in _getitem_tuple
    retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1952, in _getitem_axis
    return self._getitem_iterable(key, axis=axis)
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1593, in _getitem_iterable
    keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False)
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1550, in _get_listlike_indexer
    self._validate_read_indexer(
  File "C:\ProgramData\Anaconda3\envs\padnas1\lib\site-packages\pandas\core\indexing.py",
line 1652, in _validate_read_indexer
    raise KeyError(
KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported

, see https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-

reindex-listlike'

キーエラーが発生。これはこれで厳密でよいかもしれない。
対応としては、事前に列にそのキーが存在しているか調べた方がよさそうだ。

最後に

今回、たまたま見つかった2例を紹介したが、他にも細かいところで多々動作が変わっていると思われるので、以下などにより、網羅的に変更点を確認した方がよいだろう。
https://pandas.pydata.org/docs/whatsnew/v1.0.0.html

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