Pandas DataFrame Attributes: Inspect and Select

Inspect DataFrame labels, types, dimensions, values and styling; select by label or position and replace removed legacy attributes.

Choose an inspection or selection task 🔝

Select an operation below for the full examples. The reference material further down remains available.

Inspect labels, types and dimensions

  • columns — Inspect column labels and select or rename fields.
  • dtypes — Inspect the type of each column.
  • shape, size and ndim — Check table dimensions and element counts.
  • info() — Summarise types and non-missing counts.

Select or update values

  • loc — Select by labels or Boolean conditions.
  • iloc — Select by integer position.
  • at — Read or update one value by label.

Continue by task

Create the original six-student table 🔝

Retain Ravi, Raju, Alex, Ron, King and Jack with the original ID and subject marks. This table is embedded practice data.
Python DataFrame showing rows and columns
import pandas as pd
my_data = pd.DataFrame({"NAME": ["Ravi", "Raju", "Alex", "Ron", "King", "Jack"],
    "ID": [1, 2, 3, 4, 5, 6], "MATH": [30, 40, 50, 60, 70, 80],
    "ENGLISH": [20, 30, 40, 50, 60, 70]})
print(my_data)
assert my_data.shape == (6, 4)

Expected output

   NAME  ID  MATH  ENGLISH
0  Ravi   1    30       20
1  Raju   2    40       30
2  Alex   3    50       40
3   Ron   4    60       50
4  King   5    70       60
5  Jack   6    80       70

Discover attributes and methods 🔝

dir(pd) lists module names; dir(my_data) lists names available on the table. Discovery is not a substitute for checking signatures and documentation. Print a selected stable subset rather than a version-dependent full catalogue.
names = dir(my_data)
print([name for name in ["columns", "index", "shape", "size", "ndim", "empty", "dtypes", "loc", "iloc"] if name in names])
assert all(name in names for name in ["columns", "loc", "shape"])
assert "DataFrame" in dir(pd)

Expected output

['columns', 'index', 'shape', 'size', 'ndim', 'empty', 'dtypes', 'loc', 'iloc']

Transpose rows and columns with T 🔝

T swaps the two axes. A mixed text/numeric transpose may require a common object dtype. It returns a table, without altering my_data.
transposed = my_data.T
print(transposed)
assert transposed.shape == (4, 6)
assert transposed.loc["MATH", 2] == 50
assert my_data.shape == (6, 4)

Expected output

            0     1     2    3     4     5
NAME     Ravi  Raju  Alex  Ron  King  Jack
ID          1     2     3    4     5     6
MATH       30    40    50   60    70    80
ENGLISH    20    30    40   50    60    70

Read one scalar by label with at 🔝

at takes a row label and a column label; it does not interpret its row argument as an integer position. See at.
print(my_data.at[3, "ENGLISH"])
assert my_data.at[3, "ENGLISH"] == 50

Expected output

50

Inspect column labels 🔝

columns returns an Index, not a Python list. Convert explicitly with tolist() when a list is required. See columns.
print(my_data.columns)
print(my_data.columns.tolist())
assert my_data.columns.tolist() == ["NAME", "ID", "MATH", "ENGLISH"]

Expected output

Index(['NAME', 'ID', 'MATH', 'ENGLISH'], dtype='str')
['NAME', 'ID', 'MATH', 'ENGLISH']

Inspect each column dtype 🔝

dtypes is an attribute, so do not call dtypes(). In Pandas 3.0 inferred text often has str dtype; older versions commonly used object. Consult dtypes and info().
print(my_data.dtypes)
assert pd.api.types.is_integer_dtype(my_data["MATH"])
assert my_data["NAME"].iloc[0] == "Ravi"

Expected output

NAME         str
ID         int64
MATH       int64
ENGLISH    int64
dtype: object

Distinguish empty tables from missing values 🔝

empty is true when either axis has length zero. A table filled with missing values still has cells and is not empty. Use isna() for missing values.
print("Student table empty:", my_data.empty)
print("No rows:", my_data.iloc[:0].empty)
print("No columns:", my_data.iloc[:, :0].empty)
missing = pd.DataFrame({"mark": [float("nan")]})
print("All-missing table empty:", missing.empty)
assert not missing.empty and missing.isna().all().all()

Expected output

Student table empty: False
No rows: True
No columns: True
All-missing table empty: False

Read one scalar by integer position with iat 🔝

iat uses zero-based row and column positions. Original row position 2, column position 3 gives the ENGLISH mark 40.
print(my_data.iat[2, 3])
assert my_data.iat[2, 3] == 40

Expected output

40

Select rows and columns by position with iloc 🔝

iloc supports integer positions and slices; the slice end is excluded. See iloc.
selected = my_data.iloc[1:3, [0, 2]]
print(selected)
assert selected["NAME"].tolist() == ["Raju", "Alex"]

Expected output

   NAME  MATH
1  Raju    40
2  Alex    50

Inspect and choose row labels 🔝

The original table has a RangeIndex. Labels and positions may coincide initially but can diverge after setting an index. See set_index().
print(my_data.index)
labeled = my_data.set_index("ID")
print("Label 3 MATH:", labeled.at[3, "MATH"])
print("Position 3 MATH:", labeled.iloc[3]["MATH"])
assert labeled.at[3, "MATH"] == 50
assert labeled.iloc[3]["MATH"] == 60

Expected output

RangeIndex(start=0, stop=6, step=1)
Label 3 MATH: 50
Position 3 MATH: 60

Replace removed is_copy guidance 🔝

is_copy is a removed legacy diagnostic, not a method for making a copy. Use copy() when an independent table is intended. Update through a single loc operation rather than chained indexing.
independent = my_data.copy(deep=True)
independent.loc[0, "MATH"] = 99
print("Original mark:", my_data.at[0, "MATH"])
print("Copied mark:", independent.at[0, "MATH"])
assert my_data.at[0, "MATH"] == 30

Expected output

Original mark: 30
Copied mark: 99

Replace removed ix with explicit selection 🔝

ix was a removed mixed label/position indexer. Preserve its original MATH=50 example using loc[2, "MATH"]. For integer positions use iloc instead. Do not call ix in current Pandas.
print(my_data.loc[2, "MATH"])
assert my_data.loc[2, "MATH"] == 50

Expected output

50

Select rows and columns by label with loc 🔝

loc uses labels or Boolean conditions. Label slices include their end label. See loc.
print(my_data.loc[1:2, ["NAME", "MATH"]])
passed = my_data.loc[my_data["MATH"].ge(60), ["NAME", "MATH"]]
print(passed)
assert passed["NAME"].tolist() == ["Ron", "King", "Jack"]

Expected output

   NAME  MATH
1  Raju    40
2  Alex    50
   NAME  MATH
3   Ron    60
4  King    70
5  Jack    80

Compare ndim, shape and size 🔝

ndim counts axes, shape gives row/column lengths and size counts cells including missing values. A DataFrame has two axes even when empty. See shape, size and ndim. Original #ndim, #shape and #size anchors remain available.
print("ndim:", my_data.ndim)
print("shape:", my_data.shape)
print("size:", my_data.size)
assert my_data.ndim == 2 and my_data.size == 24
assert my_data.size == my_data.shape[0] * my_data.shape[1]

Expected output

ndim: 2
shape: (6, 4)
size: 24

Access a Styler for HTML presentation 🔝

style returns a Styler; printing its object representation is not a rendered table. Jinja2 is an optional required dependency for this accessor. If unavailable, install Jinja2 and rerun this cell. HTML generation is checked when installed; visual appearance still needs a notebook/browser preview. See table styling.
import importlib.util
if importlib.util.find_spec("jinja2") is None:
    print("Styler HTML skipped: install Jinja2, then rerun this cell")
else:
    styled = my_data.style.format({"MATH": "{:.0f}", "ENGLISH": "{:.0f}"})
    table_html = styled.to_html()
    assert "<table" in table_html and "Ravi" in table_html
    print("Styler HTML generated and checked")
assert my_data.at[0, "MATH"] == 30

Expected output

Styler HTML skipped: install Jinja2, then rerun this cell

Convert values to a NumPy representation 🔝

Retain values and prefer to_numpy() for explicit dtype/copy choices. Arrays lose axis labels, and mixed types usually share object dtype. copy=True requests a copy; converting to NumPy does not preserve a schema of separate Pandas column dtypes. See NumPy conversion.
print(my_data.values)
array = my_data.to_numpy(copy=True)
print("Array shape:", array.shape)
print("Array dtype:", array.dtype)
assert array.shape == (6, 4) and array[2, 0] == "Alex"
assert array[2, 2] == 50

Expected output

[['Ravi' 1 30 20]
 ['Raju' 2 40 30]
 ['Alex' 3 50 40]
 ['Ron' 4 60 50]
 ['King' 5 70 60]
 ['Jack' 6 80 70]]
Array shape: (6, 4)
Array dtype: object

Exercise: inspect a subset 🔝

Select King and Jack with NAME and MATH, check dimensions and read Jack's mark by label.

Exercise solution 🔝

Keep row labels when selecting the subset.
subset = my_data.loc[my_data["NAME"].isin(["King", "Jack"]), ["NAME", "MATH"]]
print(subset)
print("Shape:", subset.shape)
print("Jack mark:", subset.at[5, "MATH"])
assert subset.shape == (2, 2) and subset.at[5, "MATH"] == 80

Expected output

   NAME  MATH
4  King    70
5  Jack    80
Shape: (2, 2)
Jack mark: 80

Practice in Google Colab 🔝

Open in Google Colab View on GitHub

Run examples in order, inspect table attributes and try the exercise. Save a copy to keep edits.

Reference: Pandas DataFrame Attributes documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer