Random Python Question #6

When loc and iloc can give same output?

Let’s take an example:

what is the output of loc[1] for the above Data Frame?

When we use iloc[1], the output is:

That is, the output is same for both loc and iloc.

Please note: We need to provide label as input for data filtering for loc. However iloc uses index to filter the data.

In the above example, we have used 1 as the label in loc which gives the output for the label 1 from the given dataset.

Similarly, iloc[1] fetches the data for the index 1 which is the same as the loc[1] data in the above example.

Let us look into another Data Frame.

What is the output for loc[1] and iloc[1]?

Will that be the same or different?

Here, loc[1] fetches the data for label 1 (James, Chennai, 84) which is in the 4th row (3rd index in Python).

However, iloc[1] gets the data related to index 1 (Vicky, Mumbai, 98) which is in the 2nd row (1st index in Python). Here index is used and not the label 1.

So, when loc[1] and iloc[1] give same results?

If both label and index are the same, then both will give the same output. For this question, if the index 1 (second row) got the label as 1 then the results of loc[1] and iloc[1] will be the same.

That’s all for this question. See you next time.

Leave a comment

Design a site like this with WordPress.com
Get started