Pandas Slicing & Dicing
Load the Dataset
import pandas as pd
bank = pd.read_csv("/content/bank_market.csv")
bank.bank.shape # dimensions of the dataset
(45211, 18)
bank.head()
| Cust_num | age | job | marital | education | default | balance | housing | loan | contact | day | month | duration | campaign | pdays | previous | poutcome | y | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 58 | management | married | tertiary | no | 2143 | yes | no | unknown | 5 | may | 261 | 1 | -1 | 0 | unknown | no |
| 1 | 2 | 44 | technician | single | secondary | no | 29 | yes | no | unknown | 5 | may | 151 | 1 | -1 | 0 | unknown | no |
| 2 | 3 | 33 | entrepreneur | married | secondary | no | 2 | yes | yes | unknown | 5 | may | 76 | 1 | -1 | 0 | unknown | no |
| 3 | 4 | 47 | blue-collar | married | unknown | no | 1506 | yes | no | unknown | 5 | may | 92 | 1 | -1 | 0 | unknown | no |
| 4 | 5 | 33 | unknown | single | unknown | no | 1 | no | no | unknown | 5 | may | 198 | 1 | -1 | 0 | unknown | no |
Business Requirement
Suppose the bank manager asks:
Give me customers who are above 40 years old, have more than 5000 balance, don't have a personal loan and subscribed to our campaign.
We don't want the entire dataset. We want a specific portion.
What is Slicing & Dicing?
Slicing
Slicing means selecting a portion of rows or columns.
Dicing
Dicing means applying multiple conditions to get a very specific portion of data.
Think of Pizza
- Slicing → take 2 slices from the pizza.
- Dicing → from those slices, choose only pieces containing cheese + mushroom + no olives.
Slicing → Where in the table
Dicing → Which records satisfy my business requirement
Basic Column Slicing
bank["age"] # this returns a Series
type(bank["age"])
<class 'pandas.core.series.Series'>
Select multiple columns. Suppose the bank only wants age, job and balance:
bank[["age", "job", "balance"]].head()
bank[["age", "job", "balance"]].tail()
Row Slicing
bank[0:5] # display rows from 0,1,2,3,4
bank[10:20] # rows 10 to 19
bank.head(10) # first 10 customers
bank[0:10]
bank.tail(10) # last 10 records
loc – Label based slicing
df.loc[rows, columns]
bank.loc[[0, 1, 10, 2000]]
bank.loc[[0, 1, 10, 2000], ["age", "job", "default"]]
bank.loc[:, "age":"balance"]
bank.loc[:, ["age", "job"]]
: means take all rows.df.loc[:, ["age","job"]] → all customers, but only show age and job columns.
iloc – Integer position based slicing
df.iloc[row_positions, column_positions]
bank.iloc[0, 0] # first row, first column
bank.iloc[[0, 5, 6], [1, 5, 11, 15, 4]]
bank.iloc[-1] # last row
bank.iloc[-5:] # last five rows
bank.iloc[:, -1] # last column
iloc uses integer positions (0-based index).Negative indexing works just like in Python lists.
Boolean Filtering
bank[bank["age"] > 40]
bank[bank["balance"] > 5000]
bank[bank["loan"] == "no"]
Multiple Conditions (AND)
bank[(bank["age"] > 40) & (bank["balance"] > 5000)]
bank[(bank["age"] > 40) &
(bank["balance"] > 5000) &
(bank["loan"] == "no")]
& for AND condition.Always put each condition inside parentheses.
OR Condition
bank[(bank["age"] < 25) | (bank["age"] > 60)]
| for OR condition.isin() Method
bank[bank["job"].isin(["management", "admin.", "technician"])]
bank["job"].unique()
bank[~bank["job"].isin(["management", "technician"])]
isin() is a cleaner way to check multiple values.~ means NOT.
between() Method
bank[bank["age"].between(30, 40)]
bank[bank["balance"].between(5000, 20000)]
bank[(bank["age"].between(30, 50)) &
(bank["balance"].between(5000, 20000)) &
(bank["loan"] == "no")]
between() is a clean way to filter a range of values.loc with Conditions + Column Selection
bank.loc[bank["age"] > 40, ["age", "job", "balance", "loan"]]
bank.loc[
(bank["age"].between(30, 50)) &
(bank["balance"] > 10000) &
(bank["loan"] == "no"),
["age", "job", "marital", "balance", "loan"]
]
loc statement.query() – SQL like filtering
bank.query("age > 40")
bank.query("age > 40 and balance > 5000")
bank.query("age >= 30 and age <= 50 and balance > 10000")
query() allows writing conditions in a more readable, SQL-like style.Sorting Results
result = bank[(bank["age"] > 40) & (bank["balance"] > 5000)]
result.sort_values(by="balance", ascending=False)
result.sort_values(by="balance", ascending=False).head(10)
bank.nlargest(10, "balance")
bank.nsmallest(10, "balance")
bank.iloc[::2] # every alternate row
bank.iloc[::-1] # reverse the dataframe
sort_values() sorts the DataFrame.nlargest() and nsmallest() are convenient shortcuts.
Final Business Requirement
The bank marketing department wants customers for a premium campaign:
- Age → 30 to 50
- Balance → above 10,000
- Personal loan → No
- Housing loan → No
- Job → management / technician / admin.
- Previous campaign → Successful
bank[
(bank["age"].between(30, 50)) &
(bank["balance"] > 10000) &
(bank["loan"] == "no") &
(bank["housing"] == "no") &
(bank["job"].isin(["management", "technician", "admin."])) &
(bank["poutcome"] == "success")
]
Pandas Slicing & Dicing
Selecting rows, columns and filtering data with multiple conditions.
Select any topic from the left sidebar to begin.
Start Learning →
