IX索引器已弃用

警告

Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

.ix offers 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 recommended methods of indexing are:

  • .loc if you want to label index.
  • .iloc if you want to positionally index.
  1. In [97]: dfd = pd.DataFrame({'A': [1, 2, 3],
  2. ....: 'B': [4, 5, 6]},
  3. ....: index=list('abc'))
  4. ....:
  5. In [98]: dfd
  6. Out[98]:
  7. A B
  8. a 1 4
  9. b 2 5
  10. c 3 6

Previous behavior, where you wish to get the 0th and the 2nd elements from the index in the ‘A’ column.

  1. In [3]: dfd.ix[[0, 2], 'A']
  2. Out[3]:
  3. a 1
  4. c 3
  5. Name: A, dtype: int64

Using .loc. Here we will select the appropriate indexes from the index, then use label indexing.

  1. In [99]: dfd.loc[dfd.index[[0, 2]], 'A']
  2. Out[99]:
  3. a 1
  4. c 3
  5. Name: A, dtype: int64

This can also be expressed using .iloc, by explicitly getting locations on the indexers, and using positional indexing to select things.

  1. In [100]: dfd.iloc[[0, 2], dfd.columns.get_loc('A')]
  2. Out[100]:
  3. a 1
  4. c 3
  5. Name: A, dtype: int64

For getting multiple indexers, using .get_indexer:

  1. In [101]: dfd.iloc[[0, 2], dfd.columns.get_indexer(['A', 'B'])]
  2. Out[101]:
  3. A B
  4. a 1 4
  5. c 3 6