0

EDIT: This question should not be closed as it is completely different to the supposedly similar question. My question is about an apparent discrepancy between documentation and actual behaviour and the the other question does not help.

It says in the docs that

A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).

However, in the following example:

# Create a dictionary containing our data
cars = {
    "Model": [
        "Vauxhall Corsa",
        "Kia Sportage",
        "Nissan Qashqai",
        "Ford Fiesta",
        "Volvo XC40",
    ],
    "Sales": [3078, 2986, 2835, 2594, 2201],
}

# Create a pandas dataframe from the data in `cars`
df = pd.DataFrame(cars, columns=["Model", "Sales"])

# Display the dataframe
print(df.loc[0])

I get the output:

Model    Vauxhall Corsa
Sales              3078
Name: 0, dtype: object

I wasn't aware that my dataframe had a label of 0, and the code seems to be fetching row 0.

Can someone explain how the description of the behaviour and the result are not contradictory please?

In general, does df.loc[n], retrieve row n, or is that a misunderstanding?

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

0 Answers0