.loc Issue for line chart

Hello,
I had a question about coding in the “Exploratory Data Visualization” in the 7th screen of the “Line Charts Mission”

Screen Link: Learn data science with Python and R projects

Correct Code:
first_twelve = unrate[0:12]
plt.plot(first_twelve['DATE'], first_twelve['VALUE'])
plt.show()

My Code:
first_12_rows = unrate.loc[0:12]
plt.plot(first_12_rows["DATE"],first_12_rows["VALUE"])
plt.show()

I expected to get the same answer, however, my graph was a little different. When I took the “.loc”
away it was fine. Why is this so?

First, print out unrate.loc[0:12] and unrate[0:12] and see where they are different.

Then, look at loc’s documentation to check what exactly loc (including the examples) does and relate that to what you printed out above.

If you still feel stuck or have questions, let me know.

Hi @the_doctor,
I just saw the difference between the two (.loc vs having none) when I printed it out. I read the documentation but I’m still confused. I went back and forth between the documentation and the “Intro to pandas” mission. I thought df.loc["row2":"row3"] and df["row2":"row3"] were the same thing. I don’t know what I’m missing.

The difference would have shown you that one approach results in 12 rows while the other in 13 rows.

The documentation states -

Access a group of rows and columns by label(s) or a boolean array.

loc uses labels and not indices to access rows and columns. That’s the differentiating factor.

It further has the following example -

Getting values on a DataFrame with an index that has integer labels
df.loc[7:9]
both the start and stop of the slice are included.

Since loc accesses based on labels the start and stop of the slice are included in Pandas.

So, df.loc["row2":"row3"] and df["row2":"row3"] are not the same thing. df["row2":"row3"] accesses based on the index defined by row2 and row3 and it excludes row3. But iloc does not do that.

Hopefully, this clarifies it for you.

1 Like

@the_doctor ,
Thanks for the clarification. As soon as I saw “label(s)” I slapped my forehead! I get it now and it my first_twelve= works using .iloc[]. Thanks again.