ByteBoard Notes Notes

Create a DataFrame for examination results and display its row labels, column labels, data types and dimensions

Informatics Practices XII · Experiment 09 of 38 · Pandas

★ CBSE suggested12-IPPandas programs
Expt. No.09
Page No.18

Exam result: labels, dtypes, shape

Aim

To write a Python program that creates an examination result DataFrame and displays its row labels, column labels, the data type of each column and its dimensions.

Concepts used

Algorithm

  1. Create a dictionary of lists (Name and three subjects) and a list of roll numbers for the index.
  2. Create the DataFrame.
  3. Display df.index, df.columns, df.dtypes, df.shape and df.ndim.

Program

# Examination result: row labels, column labels, data types and dimensions import pandas as pd result = {"Name": ["Asha", "Rohan", "Ira", "Kabir"],          "English": [82, 67, 88, 74],          "Maths": [91, 58, 79, 85],          "IP": [95, 72, 90, 81]}df = pd.DataFrame(result, index=[101, 102, 103, 104])print(df)print("Row labels   :", df.index)print("Column labels:", df.columns)print("Data types:")print(df.dtypes)print("Shape (rows, columns):", df.shape)print("Number of dimensions :", df.ndim)

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

Output

$ python dataframe_attributes.py
Name English Maths IP 101 Asha 82 91 95 102 Rohan 67 58 72 103 Ira 88 79 90 104 Kabir 74 85 81 Row labels : Index([101, 102, 103, 104], dtype='int64') Column labels: Index(['Name', 'English', 'Maths', 'IP'], dtype='object') Data types: Name object English int64 Maths int64 IP int64 dtype: object Shape (rows, columns): (4, 4) Number of dimensions : 2

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

Result

The DataFrame has 4 rows and 4 columns (shape (4, 4), 2 dimensions). The row labels are the roll numbers 101–104; Name has dtype object (text) and the three subjects int64.

Viva voce: what the examiner may ask

01What does df.shape return?

A tuple (rows, columns).

02What does dtype object mean for the Name column?

The column holds text (Python strings).

03What is the difference between shape and ndim?

shape gives the size of each dimension; ndim gives how many dimensions there are (2 for a DataFrame).

Variations for the lab test

  1. Display df.size (total number of values).
  2. Display df.empty and explain the result.
  3. Add a decimal column and check its dtype.
! Common mistake Writing df.shape() with brackets raises TypeError; shape is an attribute, not a method.
Back to the 12-IP index