When to use iloc vs head

Screen link: https://app.dataquest.io/m/139/introduction-to-k-nearest-neighbors/7/average-price

Hi there,

I’m wondering when I should use iloc[] get a certain range of values vs head()

I get mixed up on when to use them. Appreciate some clarity on this. Thanks!

I would recommend first checking out their respective documentations to understand what each of it does because they are completely different use-cases -

If you still have confusion around those two, you can -

  • Go back to the introductory Pandas Missions which introduce those two
  • Experiment with the two and print out values/their output to see what they return and when
  • Ask specific questions if you get stuck once you have experimented a bit on your own
1 Like

Thanks for the reply.

It looks like iloc() is for indexing rows or columns in a dataframe or series and
head() is just for returning rows for the dataframe or series based on the position.

The difference is in selecting vs displaying

1 Like

Hey Elisha, you"re on the right track here! df.head(n) and df.iloc's results look similar on the first glance! In fact head() ALSO returns the selected rows which means in theory you could go ahead and save them to a variable. It’s not best practice though. Since head() provides less flexibility it should be used to get a glance on the dataset. I use it all the time when I make some changes like adding or removing or transforming columns and then want to get a quick look at the data. df.iloc or df.loc should be used if you want to actually select and save or manipulate data since it’s more explicit and requires less resources. While it is tempting to use head (believe me I’ve done this a lot :smiley:) it would be better for your learning to get into the habit of using iloc and it"s underlaying syntax instead.
Hope this could help!

1 Like