Exploring Data with pandas: Intermediate Page 10

Screen Link:

My Code:
For the practice question on page 10, I used the following code:

top_japanese_employer = sorted_rows.iloc[0].loc[:,"company"]

Why does my code not work, but the below does? Isn’t the code below simply using the shortcut notation for loc?

top_japanese_employer = sorted_rows.iloc[0]["company"]

Link to course: https://app.dataquest.io/m/292/exploring-data-with-pandas%3A-intermediate/10/sorting-values

Hi @56anna!

Could you add a link to the course?

Here it is: https://app.dataquest.io/m/292/exploring-data-with-pandas%3A-intermediate/10/sorting-values

The probable reason is the datatype of the sorted_rows.iloc[0].

The code:

top_japanese_employer = sorted_rows.iloc[0].loc[:,"company"]

doesn’t work is probably due to the number of indexers, i.e.:

top_japanese_employer = sorted_rows.iloc[0]

is not a pandas.DataFrame anymore with [rows, columns] structure.
Instead it is a pandas.Series which can be accessed by the 1 index only.

In this case, you need only drop the first indexer (:), which is a placeholder for choose all (in the case of loc[:,"company"] this would mean: locate all rows with column name “company”).

So “company” data from sorted_rows.iloc[0] can be accessed by:

  1. .loc:
  1. .iloc:

Hope this solves the problem.

1 Like

Thank you so much for the detailed explanation