pandas中df.ix, df.loc, df.iloc 的使用场景以及区别
pandas中df.ix, df.loc, df.iloc 的使用场景以及区别:
https://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation
# Note: in pandas version 0.20.0 and above, ix is deprecated and the use of loc and iloc is encouraged instead.
# First, a recap:
● loc works on labels in the index.
● iloc works on the positions in the index (so it only takes integers).
● ix usually tries to behave like loc but falls back to behaving like iloc if the label is not in the index.
# Combining position-based and label-based indexing
>>> df = pd.DataFrame(np.nan,
index=list('abcde'),
columns=['x','y','z', 8, 9])
>>> df
x y z 8 9
a NaN NaN NaN NaN NaN
b NaN NaN NaN NaN NaN
c NaN NaN NaN NaN NaN
d NaN NaN NaN NaN NaN
e NaN NaN NaN NaN NaN
>>> df.ix[:'c', :4]
x y z 8
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c NaN NaN NaN NaN
>>> df.iloc[:df.index.get_loc('c') + 1, :4]
x y z 8
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c NaN NaN NaN NaN
# get_loc() is an index method meaning "get the position of the label in this index".
# Note that since slicing with iloc is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well