ByteBoard Notes Notes

Select rows and columns of a DataFrame by label using loc[]

Informatics Practices XII · Experiment 11 of 38 · Pandas

12-IPPandas programs
Expt. No.11
Page No.22

Selecting with loc[]

Aim

To write a Python program that selects columns of a DataFrame by name and rows and columns by label using loc[].

Concepts used

Algorithm

  1. Create a DataFrame with index S1–S4.
  2. Select one column, then two columns with a list.
  3. Use loc to select one row, one value, and a block of rows and columns.

Program

# Selecting data by label with loc[] import pandas as pd df = pd.DataFrame({"Name": ["Asha", "Rohan", "Ira", "Kabir"],                   "Class": ["XII", "XII", "XI", "XI"],                   "Marks": [82, 67, 88, 91]},                  index=["S1", "S2", "S3", "S4"])print("Column Name:")print(df["Name"])print("Columns Name and Marks:")print(df[["Name", "Marks"]])print("Row S2:")print(df.loc["S2"])print("Marks of S3:", df.loc["S3", "Marks"])print("Rows S1 to S3, columns Name and Marks:")print(df.loc["S1":"S3", ["Name", "Marks"]])

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python dataframe_loc.py
Column Name: S1 Asha S2 Rohan S3 Ira S4 Kabir Name: Name, dtype: object Columns Name and Marks: Name Marks S1 Asha 82 S2 Rohan 67 S3 Ira 88 S4 Kabir 91 Row S2: Name Rohan Class XII Marks 67 Name: S2, dtype: object Marks of S3: 88 Rows S1 to S3, columns Name and Marks: Name Marks S1 Asha 82 S2 Rohan 67 S3 Ira 88

✓ Printed by running this program, not typed by hand.

Result

A single column came out as a Series and a list of columns as a DataFrame. loc["S2"] returned Rohan's row, loc["S3", "Marks"] the single value 88, and loc["S1":"S3", ...] included S3.

Viva voce: what the examiner may ask

01What does df.loc[row_label, column_label] return?

The value at that row and column.

02Is the end label included in a loc slice?

Yes. "S1":"S3" includes S3.

03What is the difference between df["Name"] and df[["Name"]]?

The first returns a Series; the second returns a DataFrame with one column.

Variations for the lab test

  1. Display the Class of every student from S2 to S4.
  2. Change Kabir's marks to 93 using loc.
  3. Display rows S1 and S4 only.
! Common mistake Writing df.loc["S1":"S3", "Name", "Marks"] without a list for the columns raises an error; several columns go in [ ].
Back to the 12-IP index