Week 10 Pandas Dataframes Accessing a row by giving row index

In the example given in the video for week 10 at timesyamp 7:15, df["Earth’] cannot access the row with index ‘Earth’, but df[‘Earth’:‘Earth’] works. Any reason why this should work?

It should work fine, can you share your snippet or a link to the notebook?

Hi Ishvinder,

‘df[‘Earth’]’ gives a key error
KeyError: ‘Earth’

But

'df[“Earth”:“Earth”] ’ gives the following output
|Mass |Diameter|
|Earth|5.97 |12756|
i.e it returns the row labelled Earth

I can understand that df[“Earth”] doesn’t work since pandas looks for a column named “Earth” and since there is no such column, it returns a key error.

What I cannot wrap my head around is that why should a range work. i.e. when we give a range([“Earth”: “Earth”], pandas seems to check both in column and row names and is able to resolve the command to mean get the row named “Earth”. Why is that?

1 Like

Hi @rajeevaurseema,
I don’t think it’s taking it as a range, rather it’s considering it as a key-vqlue pair.
Please check this for a better understanding.
After checking this, maybe you can try out similar things with the earth data.

Hi Ishvinder,
I dont think you are getting my question. My question is based upon the undertanding that Pandas dataframes can be thought of in two of the many other possible ways. First way to think of them is as a collection of series i.e. where each row is treated as a series. The second way is to think of them as a dictionary, where each column is a key - value pair, with the column label as the key and the contents of the column as the values. With this understanding it is logical that df[‘Mass’] should work (since now ‘Mass’ is taken as a key and pandas looks among the column labels and once it finds the key, it returns the value. It is also logical that df[“Mass” : “Diameter”] should work and return the values for all keys between “Mass” and “Diameter”. It is also logical that df[“Earth”] should return a key error since “Earth” is not one of the keys (column names). But why should df[“Earth”:“Earth”] or for that matter df[“Earth” : “Saturn”] work? When a range of row indices is given pandas seems to treat each row also as a key : value pair, with the indices being taken as keys and contents of the corresponding row being taken as values. I would appreciate it you could escalate this to the worthy professor and give a satisfactory answer.
thanks and regards