Using iloc vs loc for Figure 1 and Figure 2

Hello,
I had two questions about different coding styles in the “Exploratory Data Visualization Course,” “Multiple Plots Mission,” Page 5.

Screen Link: Learn data science with Python and R projects

My Code:
figure_1.plot(unrate.iloc[0:12]["DATE"],unrate.iloc[0:12]["VALUE"])
figure_2.plot(unrate.iloc[12:24]["DATE"],unrate.iloc[12:24]["VALUE"])
This above code gave me the correct answer.

figure_1.plot(unrate.loc["DATE"][0:12],unrate.loc["VALUE"][0:12])
figure_2.plot(unrate.loc["DATE"][12:24],unrate.loc["VALUE"][12:24])
This above code did NOT work.

My two questions are: 1) How are we able to put the label (i.e., ["DATE]) and a slice (i.e., [0:12]) together? Is this index chaining? This was the first time I saw this type of combination. 2) Why does one code work and the other doesn’t. In other words, why is using iloc ok but not loc?

1 Like

With loc or iloc if you want to index based on column names (axis=1) you will have to provide slicing for first row and then for column. (like df.loc[index_for_row, index_for_columns]) Column part comes second so to make it will have to do
unrate.loc[:, "DATE"][0:12] instead of just unrate.loc["DATE"][0:12]

as Date is column not row index.

so it would be

figure_1.plot(unrate.loc[:, "DATE"][0:12],unrate.loc["VALUE"][0:12])
figure_2.plot(unrate.loc[:, "DATE"][12:24],unrate.loc["VALUE"][12:24])

Hope it helps! I don’t know will it make clear your doubt or not.

1 Like

Hi @DishinGoyani ,
figure_1.plot(unrate.loc[:, "DATE"][0:12],unrate.loc[:,"VALUE"][0:12])
figure_2.plot(unrate.loc[:, "DATE"][12:24],unrate.loc[:,"VALUE"][12:24])

I tried this and it worked. Thanks for the explanation.

1 Like