Python Tips — iloc & loc vs iloc

Image by Author

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.
Image by Author

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

Image by Author

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.

Image by Author

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

Loc Vs iLoc:

Image by Author

Today we learned about iloc.

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

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

Happy Programming!🎈

Originally published at https://devskrol.com on September 2, 2020.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store