Не работает frame.ix
Пишу:
frame.ix[[0,1,2], ["Name", "City"]]
Получаю ошибку:
AttributeError Traceback (most recent call last)
<ipython-input-25-c18649817b31> in <module>
----> 1 frame.ix[[0,1,2], ["Name", "City"]]
D:\AnacondaPython\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5272 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5273 return self[name]
-> 5274 return object.__getattribute__(self, name)
5275
5276 def __setattr__(self, name: str, value) -> None:
AttributeError: 'DataFrame' object has no attribute 'ix'
Это можно починить?
Ответы (2 шт):
Начиная с версии Pandas 0.20.0 (дата релиза: 05.05.2017), "indexer" DataFrame.ix[] объявлен устаревшим:
Deprecate
.ixThe
.ixindexer is deprecated, in favor of the more strict.ilocand.locindexers..ixoffers a lot of magic on the inference of what the user wants to do. To wit, .ix can decide to index positionally OR via labels, depending on the data type of the index. This has caused quite a bit of user confusion over the years. The full indexing documentation is here. (GH14218)
The recommended methods of indexing are:
.locif you want to label index.ilocif you want to positionally index.
Пример из документации:
In [122]: df = pd.DataFrame({'A': [1, 2, 3],
.....: 'B': [4, 5, 6]},
.....: index=list('abc'))
.....:
In [123]: df
Out[123]:
A B
a 1 4
b 2 5
c 3 6
[3 rows x 2 columns]
устаревший способ (.ix[]):
In [3]: df.ix[[0, 2], 'A']
Out[3]:
a 1
c 3
Name: A, dtype: int64
того же можно достичь, используя .loc[]:
In [124]: df.loc[df.index[[0, 2]], 'A']
Out[124]:
a 1
c 3
Name: A, Length: 2, dtype: int64
или .iloc[]:
In [125]: df.iloc[[0, 2], df.columns.get_loc('A')]
Out[125]:
a 1
c 3
Name: A, Length: 2, dtype: int64
пример того, как получить индексы сразу нескольких значений (для df.iloc[]):
In [22]: df.iloc[[0,2], df.columns.get_indexer(["B", "A"])]
Out[22]:
B A
a 4 1
c 6 3
Начиная версией pandas 1.0.0 был атрибут .ix навсегда удален - см. Removal of prior version deprecations/changes.
Значит, ваш код нужно изменить применением другого атрибута - .loc или .iloc:
frame.loc[[0, 1, 2], ["Name", "City"]] # вместо 0, 1, 2 нужно писать реальные имена строк
# когда они отличаются от их порядковых чисел,
или (например)
frame.iloc[[0, 1, 2], [5, 8]] # когда столбец "Name" шестой и столбец "City" девятый