<DataInsights />
  • 🏠 Home
  • 📊 SQL
  • 🐍 Python
  • 📈 Power BI
  • 📗 Excel
  • 💼 Career
  • 🎯 Interview Q&A
  • 📁 Case Study
  • 📥 Downloads
  • 🚀 My Portfolio
<DataInsights />

Practical Data Analytics tutorials covering SQL, Python, Power BI, Excel and career guidance for aspiring analysts — 100% free.

Topics

  • SQL Tutorials
  • Python Guide
  • Power BI
  • Excel Tips
  • Career Guide

Quick Links

  • 🛠️ All Tools
  • 🗓️ Archive
  • 📬 Contact
  • 🔍 Search
  • Portfolio
  • Kaggle
  • GitHub

Legal & Info

  • About
  • Contact
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • DMCA
  • Sitemap
Copyright © 2026 Data Insights by Jatin Kumar. All Rights Reserved.Built with ❤️ for Data Analysts
Home/Python/Advanced Logic Functions in Pandas...

Advanced Logic Functions in Pandas

A
August 2, 2026 Jatin Kumar 17 min read Python
Data Insights Masterclass — Part 7

Advanced Logic Functions in Pandas: Complete Guide

Data analysis mein simple filtering se kaam nahi chalta — complex conditional logic, multi-condition mapping, aur intelligent binning zaroori hoti hai. Sikhiye 6 powerful Advanced Logic functions jo aapke data transformation ko next level par le jayenge.

📑 Is Masterclass Guide Mein Aap Kya Sikhenge:

Conditional logic aur intelligent data categorization ke 6 professional tools:

  • Binary Condition: np.where() — If-Else logic ek line mein
  • Multi-Condition Mapping: np.select() — Multiple conditions ek saath handle karna
  • Equal-Width Binning: pd.cut() — Continuous data ko fixed-range bins mein todna
  • Equal-Frequency Binning: pd.qcut() — Data ko equal-sized quantile groups mein divide karna
  • Value Replacement Mapping: .map() — Dictionary-based value transformation
  • Complex Row-Level Logic: .apply() with lambda — Custom function har row par apply karna

1. np.where() — Binary Conditional Logic (If-Else)

🔍 Kya Hai: np.where() NumPy ka vectorized conditional function hai jo ek condition check karke True hone par ek value aur False hone par doosri value assign karta hai. Yeh Excel ke IF() function ka Pandas equivalent hai — lekin lakhon rows par ek second mein kaam karta hai.

🎯 Kyu Use Hota Hai: Data analysis mein binary categories banana bahut common hai — Pass/Fail, High/Low, Active/Inactive, Above Average/Below Average. Traditional Python loops se yeh kaam bahut slow hota hai. np.where() vectorized hai isliye 100x faster hai loops se.

💡 Kab Use Hota Hai: Jab bhi kisi column ko exactly 2 categories mein divide karna ho based on a single condition — salary above/below threshold, age adult/minor, score pass/fail, transaction genuine/suspicious.

💻 Real-World Code Examples:

Example 1: Employees dataset mein salary basis par "High Earner" ya "Standard" category assign karna.

import numpy as np
import pandas as pd
employees = pd.read_csv("employees.csv")
employees["Salary_Category"] = np.where(
    employees["Salary"] >= 75000,
    "High Earner",
    "Standard"
)
print(employees[["Name", "Salary", "Salary_Category"]].head())

Example 2: Bank transactions mein suspicious flag lagana — agar amount ₹1,00,000 se zyada hai toh "Suspicious" mark karna.

bank["Fraud_Flag"] = np.where(
    bank["TransactionAmount"] > 100000,
    "Suspicious",
    "Normal"
)
print(bank["Fraud_Flag"].value_counts())

📊 Expected Output:

# Salary Category:
# Name      Salary   Salary_Category
# Rahul     85000    High Earner
# Priya     45000    Standard
# Amit      120000   High Earner

# Fraud Flag:
# Normal        8756
# Suspicious     244

✅ Best Practices:

  • np.where() sirf 2 categories ke liye use karein. 3 ya zyada conditions hain toh np.select() ya nested np.where() use karein — lekin nested np.where() readability kharab karta hai.
  • NaN values par condition check karte waqt dhyan rakhein — NaN ke saath comparison False return karta hai. Pehle fillna() karein ya separate NaN handling lagayein.
  • Column creation ke saath value_counts() se verify karein ki categories expected ratio mein hain ya nahi.

💬 Crack the Interview:

Q1: np.where() aur Pandas .where() mein kya difference hai?
Ans: np.where(condition, true_val, false_val) naya array return karta hai. Pandas df['col'].where(condition, other_val) condition False hone par other_val assign karta hai aur True par original value rakhta hai — logic inverted hai. np.where() zyada intuitive hai if-else ke liye.

Q2: np.where() mein multiple conditions kaise combine karein?
Ans: Bitwise operators use karein: np.where((df['Age'] > 18) & (df['Salary'] > 50000), 'Eligible', 'Not Eligible'). Har condition ko parentheses () mein wrap karna mandatory hai.

Q3: np.where() NaN values ke saath kaise behave karta hai?
Ans: NaN ke saath koi bhi comparison (>, <, ==) False return karta hai. Matlab NaN values hamesha False branch mein jayengi. Agar NaN ko separately handle karna hai toh pehle isna() check karein ya fillna() use karein.

2. np.select() — Multi-Condition Mapping

🔍 Kya Hai: np.select() multiple conditions ko ek saath handle karta hai aur har condition ke liye alag value assign karta hai. Yeh Excel ke nested IF ya SWITCH function ka equivalent hai. Conditions list aur choices list pass karni hoti hai aur ek default value bhi set kar sakte hain.

🎯 Kyu Use Hota Hai: Real-world data mein binary categories se kaam nahi chalta. Grading systems (A/B/C/D/F), risk levels (High/Medium/Low), customer segments (Premium/Regular/New) — yeh sab multi-category problems hain. np.select() inhe cleanly handle karta hai bina nested if-else ke.

💡 Kab Use Hota Hai: Jab 3 ya zyada categories banana ho — employee performance tiers, student grading, loan risk classification, customer segmentation, BMI categorization, credit score rating bands.

💻 Real-World Code Examples:

Example 1: Employees ko salary basis par 4 performance tiers mein categorize karna.

conditions = [
    employees["Salary"] >= 100000,
    employees["Salary"] >= 70000,
    employees["Salary"] >= 40000,
    employees["Salary"] 40000
]
choices = ["Executive", "Senior", "Mid-Level", "Junior"]
employees["Tier"] = np.select(conditions, choices, default="Unknown")
print(employees[["Name", "Salary", "Tier"]].head())

Example 2: Bank customers ko transaction frequency basis par segments mein classify karna.

trans_count = bank.groupby("CustomerID")["TransactionID"].count().reset_index()
trans_count.columns = ["CustomerID", "Total_Trans"]
conditions = [
    trans_count["Total_Trans"] >= 50,
    trans_count["Total_Trans"] >= 20,
    trans_count["Total_Trans"] >= 5
]
choices = ["Power User", "Regular", "Occasional"]
trans_count["Segment"] = np.select(conditions, choices, default="Inactive")
print(trans_count["Segment"].value_counts())

📊 Expected Output:

# Employee Tiers:
# Name     Salary   Tier
# Rahul    120000   Executive
# Priya    72000    Senior
# Amit     38000    Junior

# Customer Segments:
# Regular       3420
# Occasional    2150
# Power User     890
# Inactive       540

✅ Best Practices:

  • Conditions ka order matter karta hai — pehli True condition select hoti hai. Hamesha strictest condition pehle rakhein (highest salary pehle, lowest baad mein) warna galat category assign hogi.
  • default parameter hamesha set karein — agar koi row kisi bhi condition mein match nahi kare toh default value milegi. Bina default ke 0 assign hota hai jo confusing hota hai.
  • conditions aur choices ki length exactly same honi chahiye warna ValueError aayega.

💬 Crack the Interview:

Q1: np.select() aur nested np.where() mein kya difference hai?
Ans: Dono same result de sakte hain lekin np.select() readable aur maintainable hai. Nested np.where() 3+ levels par extremely confusing ho jaata hai. np.select() conditions list mein naye conditions add karna easy hai bina nesting badhaye.

Q2: Agar multiple conditions True hain ek row ke liye toh np.select() kya karega?
Ans: np.select() FIRST matching condition ka choice select karta hai — baaki True conditions ignore hoti hain. Isliye conditions ka order critical hai — most restrictive pehle rakhein.

Q3: np.select() vs pd.cut() — kab kaunsa use karein?
Ans: np.select() flexible hai — koi bhi conditions (multiple columns, complex logic) handle kar sakta hai. pd.cut() sirf single column ke numeric ranges ke liye optimized hai. Simple binning ke liye pd.cut(), complex multi-column logic ke liye np.select().

3. pd.cut() — Equal-Width Binning (Fixed Range Bins)

🔍 Kya Hai: pd.cut() continuous numerical data ko fixed-width bins (ranges) mein divide karta hai. Aap manually bin edges define kar sakte hain ya Pandas ko automatically equal-width bins banane de sakte hain. Har row ko uski value ke basis par appropriate bin/category assign hoti hai.

🎯 Kyu Use Hota Hai: Continuous values (age, salary, marks) ko directly analyze karna mushkil hota hai. Inhe meaningful groups mein convert karne se patterns clearly dikhte hain — "25-35 age group ne sabse zyada shopping ki" ya "50000-70000 salary range mein attrition highest hai".

💡 Kab Use Hota Hai: Age group analysis, salary band creation, marks grading, price range categorization, BMI classification, credit score ranges — jab bhi fixed boundaries par numerical data ko groups mein todna ho.

💻 Real-World Code Examples:

Example 1: Employees ko age groups mein categorize karna custom bins define karke.

bins = [0, 25, 35, 45, 55, 100]
labels = ["Gen Z", "Young Professional", "Mid Career", "Senior", "Pre-Retirement"]
employees["Age_Group"] = pd.cut(
    employees["Age"],
    bins=bins,
    labels=labels
)
print(employees["Age_Group"].value_counts())

Example 2: E-commerce product prices ko 5 automatic equal-width price bands mein divide karna.

ecommerce["Price_Band"] = pd.cut(
    ecommerce["Price"],
    bins=5,
    labels=["Budget", "Economy", "Mid-Range", "Premium", "Luxury"]
)
print(ecommerce["Price_Band"].value_counts())

📊 Expected Output:

# Age Groups:
# Young Professional    3420
# Mid Career            2890
# Gen Z                 1560
# Senior                1200
# Pre-Retirement         430

# Price Bands:
# Budget       4520  # Most products are budget range
# Economy      2340
# Mid-Range    1890
# Premium       750
# Luxury        500

✅ Best Practices:

  • Manual bins define karte waqt ensure karein ki minimum value first bin se chhoti ho aur maximum value last bin se chhoti ho, warna values NaN ho jayengi.
  • Labels ki count hamesha bins count se exactly 1 kam honi chahiye. 5 bin edges = 4 labels. Galat count se ValueError aayega.
  • Default behavior right-inclusive hai: (0, 25] matlab 0 excluded, 25 included. First bin ko include karne ke liye include_lowest=True pass karein.

💬 Crack the Interview:

Q1: pd.cut() aur pd.qcut() mein fundamental difference kya hai?
Ans: pd.cut() equal-width bins banata hai (fixed ranges jaise 0-25, 25-50) — har bin ka range same hota hai lekin items count different ho sakta hai. pd.qcut() equal-frequency bins banata hai — har bin mein approximately same number of items hote hain lekin ranges different hoti hain.

Q2: pd.cut() se bana column ka dtype kya hota hai?
Ans: Categorical dtype hota hai jo memory efficient hai. Labels pass karne par ordered Categorical banta hai. df['col'].cat.codes se integer codes mil sakte hain ML models ke liye.

Q3: Out-of-range values ko kaise handle karta hai pd.cut()?
Ans: Agar koi value bins range se bahar hai toh NaN assign hota hai. Isse avoid karne ke liye bins mein -np.inf aur np.inf rakhein: bins=[-np.inf, 25, 50, np.inf] jo extreme values bhi capture karega.

4. pd.qcut() — Equal-Frequency Binning (Quantile Based)

🔍 Kya Hai: pd.qcut() (Quantile Cut) data ko equal-frequency bins mein divide karta hai — har bin mein approximately same number of observations hote hain. Bins ki ranges data distribution ke basis par automatically calculate hoti hain.

🎯 Kyu Use Hota Hai: Skewed data (jahan zyada values ek side mein concentrated hain) par pd.cut() se bahut uneven bins bante hain — ek bin mein 90% data aa jaata hai aur baaki bins almost empty rehte hain. pd.qcut() ensure karta hai ki har group mein comparable data volume ho jo fair analysis ke liye zaroori hai.

💡 Kab Use Hota Hai: Customer ranking (Top 25%, Bottom 25%), percentile-based performance tiers, ML feature discretization, income percentile groups, aur jab bhi balanced groups chahiye regardless of data distribution tab qcut() use hota hai.

💻 Real-World Code Examples:

Example 1: Employees ko salary percentiles basis par 4 quartile groups mein divide karna (Top 25%, etc.).

employees["Salary_Quartile"] = pd.qcut(
    employees["Salary"],
    q=4,
    labels=["Bottom 25%", "Lower Mid", "Upper Mid", "Top 25%"]
)
print(employees["Salary_Quartile"].value_counts())

Example 2: E-commerce customers ko purchase frequency basis par equal-sized segments mein baatna.

customer_freq = ecommerce.groupby("CustomerID")["OrderID"].count().reset_index()
customer_freq.columns = ["CustomerID", "Order_Count"]
customer_freq["Frequency_Tier"] = pd.qcut(
    customer_freq["Order_Count"],
    q=3,
    labels=["Low", "Medium", "High"]
)
print(customer_freq["Frequency_Tier"].value_counts())

📊 Expected Output:

# Salary Quartiles (Equal frequency — ~25% each):
# Bottom 25%    2500
# Lower Mid     2500
# Upper Mid     2500
# Top 25%       2500

# Frequency Tiers (~33% each):
# Low      1670
# Medium   1665
# High     1665

✅ Best Practices:

  • Duplicate values bahut zyada hain toh qcut() error de sakta hai: "Bin edges must be unique". Isko fix karne ke liye duplicates='drop' parameter pass karein.
  • Custom quantile cuts ke liye list pass karein: pd.qcut(df['col'], q=[0, 0.1, 0.5, 0.9, 1.0]) jo 10th, 50th, 90th percentile par split karega.
  • Labels na pass karein toh actual bin ranges dikhte hain jaise "(20000, 45000]" — debugging ke liye useful hai.

💬 Crack the Interview:

Q1: pd.qcut() mein q=4 pass karne se exactly kya hota hai?
Ans: Data ko 4 quartiles mein divide karta hai — 25th, 50th, 75th, 100th percentile par cuts lagake. Har bin mein approximately 25% data hota hai. q=10 dene par deciles (10 equal groups), q=100 par percentiles bante hain.

Q2: qcut() mein "Bin edges must be unique" error kyun aata hai?
Ans: Jab data mein bahut zyada same values hain (ties) toh quantile boundaries same ho jaati hain — jaise 50th aur 75th percentile dono 50000 hain. duplicates='drop' lagane se duplicate boundaries merge ho jaati hain aur error resolve hota hai.

Q3: ML feature engineering mein pd.cut() ya pd.qcut() — kaunsa better hai?
Ans: Generally qcut() better hai ML ke liye kyunki equal-frequency bins ensure karte hain ki har class mein sufficient training examples hain. cut() se sparse bins ban sakte hain jinme model properly seekh nahi pata. Lekin domain knowledge ke basis par cut() better ho sakta hai.

5. .map() — Dictionary-Based Value Transformation

🔍 Kya Hai: .map() Pandas Series ka method hai jo dictionary ya function pass karke har value ko corresponding replacement value mein transform karta hai. Yeh simple one-to-one value mapping ke liye sabse clean aur readable method hai.

🎯 Kyu Use Hota Hai: Real data mein codes aur abbreviations hote hain jo human-readable nahi hote — "M"/"F" ko "Male"/"Female", department codes ko department names, country codes ko full names mein convert karna. map() ek dictionary pass karke yeh ek line mein kar deta hai.

💡 Kab Use Hota Hai: Category code expansion, label encoding/decoding, rating number to text conversion, status code mapping, aur jab bhi finite known values ko doosre values mein replace karna ho.

💻 Real-World Code Examples:

Example 1: Employee department codes ko full department names mein convert karna.

dept_mapping = {
    "HR": "Human Resources",
    "IT": "Information Technology",
    "FIN": "Finance & Accounts",
    "MKT": "Marketing",
    "OPS": "Operations"
}
employees["Department_Full"] = employees["Dept_Code"].map(dept_mapping)
print(employees[["Dept_Code", "Department_Full"]].head())

Example 2: E-commerce product ratings (1-5) ko text feedback labels mein convert karna.

rating_map = {
    1: "Very Poor",
    2: "Poor",
    3: "Average",
    4: "Good",
    5: "Excellent"
}
ecommerce["Rating_Label"] = ecommerce["Rating"].map(rating_map)
print(ecommerce["Rating_Label"].value_counts())

📊 Expected Output:

# Department Mapping:
# Dept_Code  Department_Full
# IT         Information Technology
# HR         Human Resources
# FIN        Finance & Accounts

# Rating Labels:
# Good         3240
# Average      2890
# Excellent    1560
# Poor          890
# Very Poor     420

✅ Best Practices:

  • Dictionary mein missing key ke liye map() NaN return karta hai. Agar unmapped values ko as-is rakhna hai toh .map(dict).fillna(df['original_col']) ya .replace(dict) use karein.
  • map() sirf Series par kaam karta hai, DataFrame par nahi. DataFrame ke multiple columns par mapping ke liye .replace() ya .applymap() use karein.
  • Function bhi pass kar sakte hain: df['col'].map(str.upper) ya df['col'].map(lambda x: x*2) — dictionary se zyada flexible hai.

💬 Crack the Interview:

Q1: .map() aur .replace() mein kya difference hai?
Ans: map() unmapped values ko NaN kar deta hai. replace() unmapped values ko unchanged rakhta hai. Agar sabhi values map karni hain toh map() use karein, agar kuch specific values replace karni hain toh replace() use karein.

Q2: .map() aur .apply() mein kya difference hai performance wise?
Ans: map() dictionary lookup ke liye optimized hai aur apply() se faster hai simple mappings ke liye. apply() custom complex functions ke liye hai jo multiple operations karta hai. Simple value replacement ke liye hamesha map() prefer karein.

Q3: ML mein label encoding map() se kaise karein?
Ans: encoding = {'Male': 0, 'Female': 1} dictionary banake df['Gender_Encoded'] = df['Gender'].map(encoding) use karein. Decode karne ke liye reverse dictionary banayein: {v:k for k,v in encoding.items()}.

6. .apply() with lambda — Complex Row-Level Custom Logic

🔍 Kya Hai: .apply() Pandas ka sabse flexible method hai jo custom function (ya lambda expression) ko har row ya har column par individually execute karta hai. Jab built-in functions se complex logic handle nahi hota tab apply() last resort hai — koi bhi Python logic apply kar sakte hain.

🎯 Kyu Use Hota Hai: Real-world business logic aksar multiple columns ke combination par depend karta hai — "Agar department IT hai AUR experience 5+ saal hai AUR rating A hai toh bonus 20% warna 10%". Aise multi-column complex rules ke liye apply() + lambda ya custom function zaroori hota hai.

💡 Kab Use Hota Hai: Jab np.where(), np.select(), map() — koi bhi kaam na kare tab apply() use karein. Multi-column dependent complex business rules, custom text processing, conditional calculations with exceptions, aur row-level data validation ke liye.

💻 Real-World Code Examples:

Example 1: Employee bonus calculation — multi-column logic (department + experience + rating) par based hai.

def calculate_bonus(row):
    if row["Department"] == "IT" and row["Experience"] >= 5:
        return row["Salary"] * 0.20
    elif row["Experience"] >= 3:
        return row["Salary"] * 0.12
    else:
        return row["Salary"] * 0.05

employees["Bonus"] = employees.apply(calculate_bonus, axis=1)
print(employees[["Name", "Department", "Experience", "Salary", "Bonus"]].head())

Example 2: E-commerce orders mein delivery status determine karna — order date, delivery date, aur current date compare karke.

ecommerce["Status"] = ecommerce.apply(
    lambda row: "Delivered" if pd.notna(row["DeliveryDate"])
    else ("Delayed" if (pd.Timestamp.now() - row["OrderDate"]).days > 7
    else "In Transit"),
    axis=1
)
print(ecommerce["Status"].value_counts())

📊 Expected Output:

# Employee Bonus:
# Name    Department  Experience  Salary   Bonus
# Rahul   IT          7           85000    17000.0  # 20% (IT + 5yr+)
# Priya   HR          4           65000    7800.0   # 12% (3yr+)
# Amit    IT          1           42000    2100.0   # 5% (default)

# Order Status:
# Delivered    6520
# In Transit   2340
# Delayed      1140

✅ Best Practices:

  • apply() SLOW hai compared to vectorized operations. Hamesha pehle np.where(), np.select(), ya vectorized methods try karein. apply() sirf tab use karein jab koi alternative na ho.
  • axis=1 row-wise apply karta hai (har row ek Series jaisa milta hai), axis=0 column-wise (default). Row-level logic ke liye axis=1 mandatory hai.
  • Complex logic ke liye named function define karein (Example 1 jaisa). Lambda expressions ko 2-3 lines se zyada complex mat banayein — readability bahut kharab hoti hai.

💬 Crack the Interview:

Q1: apply() kyun slow hai aur alternatives kya hain?
Ans: apply() internally Python loop chalaata hai — har row par function call ka overhead hota hai. Vectorized operations (np.where, np.select) C-level optimized hain aur 10-100x faster hain. 1M+ rows par apply() minutes lega jabki vectorized seconds mein hoga.

Q2: apply() mein axis=0 aur axis=1 ka practical difference samjhayein?
Ans: axis=0 (default): function har column par apply hota hai — column-level aggregation ke liye. axis=1: function har row par apply hota hai — row-level business logic ke liye. Row mein multiple columns access karne ke liye axis=1 zaroori hai: row['Salary'], row['Department'].

Q3: lambda vs named function — kab kaunsa use karein apply() mein?
Ans: Lambda sirf simple 1-line logic ke liye: df.apply(lambda x: x*2). Complex multi-line logic, error handling, ya multiple conditions ke liye proper named function define karein — testing, debugging, aur reusability sab better hoti hai.

Conclusion: Advanced Logic Functions Quick Reference Matrix

Apne logic requirement ke basis par sahi function chunye:

Task / Requirement Function to Use Key Note
Binary If-Else (2 categories) np.where() Vectorized, fastest option
Multiple conditions (3+ categories) np.select() Order matters — strictest pehle
Fixed-range numeric binning pd.cut() Equal-width bins, domain-driven
Equal-frequency quantile binning pd.qcut() Balanced groups, skew-resistant
Simple value replacement/mapping .map() Dictionary-based, unmapped → NaN
Complex multi-column business logic .apply() + lambda Last resort — slowest, most flexible

Next Post Preview: Masterclass Part 8

Next masterclass mein hum cover karenge: Basic EDA & Structure Functions — head(), tail(), info(), describe(), shape, dtypes aur data structure exploration ke complete tools.

Happy Coding & Stay Analytically Pure! 🚀

👤
Jatin Kumar
Data Analyst & Educator

Python, SQL, Power BI aur Excel mein practical tutorials likhta hoon — taaki data analytics seekhna aasan ho. Portfolio: jatinanalytics.co.in

Portfolio LinkedIn GitHub Kaggle All Articles
Share:

💬 Comments (0)

Spam/links allowed nahi hain — respectful comments welcome!

Loading comments...

Was this article helpful?
Previous ArticleDate and Time Functions in Pandas:Next Article Basic EDA And Structure Functions in Pandas

📚 More Articles Like This

Numeric Cleaning And Outlier Handling In Pandas

Read Article

Data Type Conversion And Mapping in Pandas

Read Article

Text Cleaning And String Sanitization In Pandas

Read Article