Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

Can someone explain how these three methods of slicing are different?

I've seen the docs, but I still find myself unable to explain how the three are different. To me, they seem interchangeable in large part, because they are at the lower levels of slicing.

For example, say we want to get the first five rows of a DataFrame. How is it that all three of these work?

df.loc[:5]

df.ix[:5]

df.iloc[:5]

Can someone present three cases where the distinction in uses are clearer?

1 Answer

0 votes
by (25.1k points)

All of these methods are used to access data in data frames.

iloc is used for integer location based indexing e,g, df.iloc[0] will select the first row in the data frame.

loc is used to select rows by label or by boolean (conditional lookup) e.g. df.loc['abcd'] will select the row based on the value of the index column with value 'abcd'

Also, we can perform boolean / conditional indexing : df[df['salary'] > 1000, ['first_name', 'last_name']], this will the rows with first_name and last_name columns with salary greater than 1000.

ix can be used as a hybrid of both loc and iloc however ix has been deprecated since pandas 0.20.1 so it's best not to use it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...