2

In pandas iloc vs ix vs loc explanation, how are they different?, it mentions that:ix usually tries to behave like loc but falls back to behaving like iloc if the label is not in the index.

For the example below, when I use ix[0], it does not work, what happened?

enter image description here

Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.

jpp
  • 159,742
  • 34
  • 281
  • 339
william007
  • 17,375
  • 25
  • 118
  • 194

2 Answers2

3

Short explanation

Consider dataframe df

df = pd.DataFrame(
    np.arange(16).reshape(4, 4),
    list('wxyz'), list('abcd'))

    a   b   c   d
w   0   1   2   3
x   4   5   6   7
y   8   9  10  11
z  12  13  14  15
  • iloc is ordinal position based indexing

    df.iloc[[0, 3], [1, 2]]
    
        b   c
    w   1   2
    z  13  14
    
  • loc is label based indexing

    df.loc[['z', 'x'], ['b', 'c']]
    
        b   c
    z  13  14
    x   5   6
    
  • ix tries to be smart and figure out what you need but is sometimes confusing and most importantly will be phased out and should not be used!!!

piRSquared
  • 285,575
  • 57
  • 475
  • 624
3

You can check docs:

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 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.

Community
  • 1
  • 1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252