From a quarterly sales DataFrame, display a chosen category and delete rows below a given expenditure
Expt. No.16
Page No.32
Filter a category, drop low rows
Aim
To write a Python program that creates a quarterly sales DataFrame (category, item, expenditure), displays the items of a chosen category with Boolean indexing, and deletes rows whose expenditure is below a given amount.
Concepts used
Algorithm
- Create the DataFrame.
- Input a category and display the rows where Category equals it.
- Input an amount; find the row labels where Expenditure is below it.
- Drop those rows with drop() and display the result.
Program
# Quarterly sales: filter a category and drop low rows import pandas as pd df = pd.DataFrame({"Category": ["Stationery", "Electronics", "Stationery", "Furniture", "Electronics", "Furniture"], "Item": ["Notebook", "Mouse", "Pen", "Chair", "Keyboard", "Table"], "Expenditure": [4500, 8200, 1200, 15000, 6400, 22000]})print(df) cat = input("Category to display: ")print(df[df["Category"] == cat]) limit = int(input("Delete rows with expenditure below: "))low_rows = df[df["Expenditure"] < limit].indexdf = df.drop(low_rows)print("After deleting:")print(df)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python dataframe_filter_drop.py
Category Item Expenditure
0 Stationery Notebook 4500
1 Electronics Mouse 8200
2 Stationery Pen 1200
3 Furniture Chair 15000
4 Electronics Keyboard 6400
5 Furniture Table 22000
Category to display: Electronics
Category Item Expenditure
1 Electronics Mouse 8200
4 Electronics Keyboard 6400
Delete rows with expenditure below: 5000
After deleting:
Category Item Expenditure
1 Electronics Mouse 8200
3 Furniture Chair 15000
4 Electronics Keyboard 6400
5 Furniture Table 22000
✓ Printed by running this program, not typed by hand.
Result
Choosing Electronics displayed Mouse and Keyboard. With a limit of 5000, the Notebook (4500) and Pen (1200) rows were dropped, leaving 4 rows with their original labels.
Viva voce: what the examiner may ask
01What does df[df["Expenditure"] < limit].index give?
The row labels of the rows that meet the condition.
02Why are the remaining row labels not 0, 1, 2, 3?
drop() keeps the original labels of the rows that remain.
03How else could the low rows be removed?
By keeping only the other rows: df = df[df["Expenditure"] >= limit].
Variations for the lab test
- Display the items of two categories using
|. - Increase the expenditure of Furniture items by 10% using loc.
- Delete the rows of a chosen category.
! Common mistake Forgetting
df = before df.drop(...): drop() returns a new DataFrame, so the original is unchanged.