Pandas

Pandas Slicing & Dicing

01 · Load Data & Shape File · Slicing & Dicing · 1 of 16

Load the Dataset

Python
import pandas as pd
bank = pd.read_csv("/content/bank_market.csv")
First we import pandas and load the bank marketing dataset into a DataFrame called bank.
Python
bank.shape  # dimensions of the dataset
Output
(45211, 18)
The dataset has 45,211 rows and 18 columns.
Python
bank.head()
Output
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
Shows the first 5 rows of the dataset.
02 · Business Requirement File · Slicing & Dicing · 2 of 16

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.

03 · What is Slicing & Dicing? File · Slicing & Dicing · 3 of 16

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

04 · Column Slicing File · Slicing & Dicing · 4 of 16

Basic Column Slicing

Python
bank["age"]  # this returns a Series
type(bank["age"])
Output
<class 'pandas.core.series.Series'>
Selecting one column returns a Series.

Select multiple columns. Suppose the bank only wants age, job and balance:

Python
bank[["age", "job", "balance"]].head()
bank[["age", "job", "balance"]].tail()
When selecting multiple columns, we pass a list of column names. This returns a DataFrame.
05 · Row Slicing File · Slicing & Dicing · 5 of 16

Row Slicing

Python
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
We can slice rows using normal Python slicing syntax.
06 · loc – Label based File · Slicing & Dicing · 6 of 16

loc – Label based slicing

df.loc[rows, columns]

Python
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.
07 · iloc – Position based File · Slicing & Dicing · 7 of 16

iloc – Integer position based slicing

df.iloc[row_positions, column_positions]

Python
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.
08 · Boolean Filtering File · Slicing & Dicing · 8 of 16

Boolean Filtering

Python
bank[bank["age"] > 40]
bank[bank["balance"] > 5000]
bank[bank["loan"] == "no"]
Boolean filtering is the most common way to select rows that satisfy a condition.
09 · Multiple Conditions (AND) File · Slicing & Dicing · 9 of 16

Multiple Conditions (AND)

Python
bank[(bank["age"] > 40) & (bank["balance"] > 5000)]
bank[(bank["age"] > 40) &
     (bank["balance"] > 5000) &
     (bank["loan"] == "no")]
Use & for AND condition.
Always put each condition inside parentheses.
10 · OR Condition File · Slicing & Dicing · 10 of 16

OR Condition

Python
bank[(bank["age"] < 25) | (bank["age"] > 60)]
Use | for OR condition.
11 · isin() Method File · Slicing & Dicing · 11 of 16

isin() Method

Python
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.
12 · between() Method File · Slicing & Dicing · 12 of 16

between() Method

Python
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.
13 · loc with Conditions File · Slicing & Dicing · 13 of 16

loc with Conditions + Column Selection

Python
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"]
]
We can combine row filtering and column selection in one loc statement.
14 · query() Method File · Slicing & Dicing · 14 of 16

query() – SQL like filtering

Python
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.
15 · Sorting Results File · Slicing & Dicing · 15 of 16

Sorting Results

Python
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.
16 · Final Campaign Filter File · Slicing & Dicing · 16 of 16

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
Python
bank[
    (bank["age"].between(30, 50)) &
    (bank["balance"] > 10000) &
    (bank["loan"] == "no") &
    (bank["housing"] == "no") &
    (bank["job"].isin(["management", "technician", "admin."])) &
    (bank["poutcome"] == "success")
]
This is the final dicing filter that satisfies the complete business requirement.
Home Pandas Slicing & Dicing

Pandas Slicing & Dicing

Selecting rows, columns and filtering data with multiple conditions.

Select any topic from the left sidebar to begin.


Start Learning →