Doubt in slicing dataframe

Screen Link:

My Code:

bottom_companies = f500['National Grid':'AutoNation', ['rank', 'sector', 'country'] ]

What I expected to happen:
I expected this code to work as we do not have to use the ‘.loc’ for when we want to select a slice of rows, or a list of columns. However the dataframe.loc has to be used to select a slice of rows and a list of columns.

1 Like

You are trying to select at the same time a slice of rows and a list of columns from the dataframe. That’s a complex operation. There is no shorthand for this, you need yo use .loc.

Actually, I think it is better to always use .iloc and .iloc. But that is only my opinion.


Try this.
bottom_companies = f500.loc[‘National Grid’:‘AutoNation’, [‘rank’, ‘sector’, ‘country’] ]

When you are trying to slice both rows and columns, use “.loc” always.

1 Like