Difference between loc and iloc?

what is the difference between loc and iloc

1 Like

loc retrieves with labels and iloc with index. For instance, if you have a cars dataframe -
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JPN 588 Japan False
IN 18 India False
RU 200 Russia True
MOR 70 Morocco True
EG 45 Egypt True

cars.loc[‘US’] or cars.iloc[0] would give the same result-
cars_per_cap 809
country United States
drives_right True
Name: US, dtype: object

If you 'd like , you cold go through this short write-up: https://www.pythonprogramming.in/what-is-difference-between-iloc-and-loc-in-pandas.html

1 Like

loc: use when you want to index based on “location” which is column or index “labels”.
iloc: use when you want to index based on “integer location” like indexing from a python list using integers.
Eg:-df
----------------------Name---------Occupation--------Salary
Individual 1---- Abhishek----------Doctor------------6500k
Individual 2------Raghu--------------CA---------------6350k

Retrieving Individual 2’s Name and Salary details using loc:
df.loc[‘Individual 2’, [‘Name’, ‘Salary’]]

Retrieving Individual 2’s Name and Salary details using iloc:
df.iloc[1, [0, 2]]

Both will retrieve will the same info.

2 Likes

There’re quite a bit of differences. I think the best shot is to go to YouTube and find a video on this topic. There’re more than a handful.

Beyond what you asked, you should be able to pick up some tricks and tips out from them. Enjoy!