Python: Pandas AttributeError: 'DataFrame' object has no attribute 'ix'
1. 问题概述:
运行以下代码:
In [39]: df Out[39]: A B C first second bar one 0.895717 0.410835 -1.413681 two 0.805244 0.813850 1.607920 baz one -1.206412 0.132003 1.024180 two 2.565646 -0.827317 0.569605 foo one 1.431256 -0.076467 0.875906 two 1.340309 -1.187678 -2.211372 qux one -1.170299 1.130127 0.974466 two -0.226169 -1.436737 -2.006747
In [45]: df.ix[[('bar', 'two'), ('qux', 'one')]]
会抛出以下错误:
Out[45]: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ... AttributeError: 'DataFrame' object has no attribute 'ix'
2. 相关原因:
从pandas 0.20.0开始,.ix索引器已被弃用,取而代之的是更严格的.iloc和.loc索引器。
.ix索引器已经从Pandas 1.0.0版本中移除。
参考:
Pandas 0.25.3
pandas.DataFrame.ix
DataFrame.
ix
A primarily label-location based indexer, with integer position fallback.
Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
.ix[]
supports mixed integer and label based access. It is primarily label based, but will fall back to integer positional access unless the corresponding axis is of integer type.
.ix
is the most general indexer and will support any of the inputs in .loc
and .iloc
. .ix
also supports floating point label schemes. .ix
is exceptionally useful when dealing with mixed positional and label based hierarchical indexes.
However, when an axis is integer based, ONLY label based access and not positional access is supported. Thus, in such cases, it’s usually better to be explicit and use .iloc
or .loc
.
See more at Advanced Indexing.
Pandas 1.0.0
https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html#removal-of-prior-version-deprecations-changes
Removal of prior version deprecations/changes
Removed Series.ix
and DataFrame.ix
(GH26438)
3. 解决办法:
使用.iloc和.loc索引器替代。