A tip A day – Python Tip #2 – iloc & loc vs iloc

Today we are going to learn how to use iloc to get values from Pandas DataFrame and we are going to compare iloc with loc.

To learn about loc, please check A tip A day – Python Tip #1 – loc.

Using iloc:

  • iLoc uses only numbers/indexes (strictly numerical values) to get values from a Pandas DataFrame.
  • Apart from numerical values, it accepts boolean arrays similar to Loc

Consider the above dataframe. It has Named index.

If a slice object is given as argument in iloc, then it returns data from starting index upto ending index, but excluding the ending index.

Also the indexes will start from 0 (Not 1).

See that the slice object “0:2” points the indexes from June (Index = 0) till July (Index = 1), but the third row August (Index = 2) was not returned.

Similarly, the index of the second column ‘apples’ is 1 and third columns ‘grapes’ (Index = 2) is returned but ‘pear’ is not returned.

As mentioned above, iloc can accept boolean list / condition statements too.

Loc Vs iLoc:

LociLoc
Strictly label basedStrictly index based
Accepts Boolean Array/ ConditionsAccepts Boolean Array/ Conditions
Includes both the ranges in slice object. Example: ‘a’:’bExcludes the end range in slice object as it uses index.
Example: 0:3 returns 0,1,2 not 3

Today we learned about iloc.

We will meet with a new tip in Python. Thank you! 👍

Like to support? Just click the heart icon ❤️.

Happy Programming!🎈

Asha Ponraj
Asha Ponraj

Data science and Machine Learning enthusiast | Software Developer | Blog Writter

Articles: 87

Leave a Reply

Your email address will not be published. Required fields are marked *