Selecting rows in pandas

My code is little bit different for the answer, the difference is at the way of selecting a row from the dataset.
why the output is different between df.iloc[1] and df[:1]
Thank you!
Screen Link: https://app.dataquest.io/m/144/bar-plots-and-scatter-plots/2/introduction-to-the-data

My Code:

import pandas as pd
reviews=pd.read_csv('fandango_scores.csv')
norm_reviews=reviews.loc[:,['FILM', 'RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']]
print(norm_reviews.iloc[1])

What I expected to happen:

                       FILM  RT_user_norm  Metacritic_user_nom  \

0 Avengers: Age of Ultron (2015) 4.3 3.55

IMDB_norm Fandango_Ratingvalue Fandango_Stars
0 3.9 4.5 5.0
What actually happened:

FILM                    Cinderella (2015)
RT_user_norm                            4
Metacritic_user_nom                  3.75
IMDB_norm                            3.55
Fandango_Ratingvalue                  4.5
Fandango_Stars                          5
Name: 1, dtype: object

Because df.iloc[1] and df[:1] are two very different things. df.iloc[1] selects only the second row of the DataFrame while df[:1] selects only the first row. Remember that indexing starts at zero.

Thank you for reply!

what does the colon mean here? For my understanding, the colon means selecting consecutive columns or row. like [1:3,2:3].
Thank you so much!

1 Like

The colon is used for slicing. You can use it on lists, tuples, dataframes, series, and more. It selects all the elements between the element before the colon (which is included) and the element after the colon (which is not included). Examples:

  • [1:4] selects elements 1, 2 and 3.
  • [0:5] selects elements 0, 1, 2, 3, 4.
  • [1:3] selects elements 1 and 2.
  • [2:3] selects element 2.
  • [1:3, 2:3] selects the rows 1 and 2 and column 2 from a dataframe.

When there’s no number after the colon, the selection returns all elements after the number before the colon. The opposite happens when there’s no number before the colon. Examples:

  • [:5] selects all elements before the element with index 5.
  • [5:] selects all elements from the element with index 5 on.
  • [:1] selects all elements before the element with index 1, which is only the element with index 0.

I hope this helps you.

Thank you for you detailed explanation! It is so helpful! thank you!!

1 Like
  • Just change you iloc value from 1 to 0. You would get your desired output. :smile:

print(norm_reviews.iloc[0])

Output:

FILM Avengers: Age of Ultron (2015)
RT_user_norm 4.3
Metacritic_user_nom 3.55
IMDB_norm 3.9
Fandango_Ratingvalue 4.5
Fandango_Stars 5