Concept Explanation
If NumPy is the high-performance engine of data science, Pandas is the luxurious, feature-packed dashboard.
Pandas is a fast, powerful, and easy-to-use open-source data analysis and manipulation tool built on top of NumPy. It is the "go-to" library for anyone working with tabular data (like Excel spreadsheets or SQL tables). While NumPy works best with numbers, Pandas is designed to work with labeled data—meaning your columns have names like "Price," "Date," or "Customer Name."
The Two Pillars of Pandas:
- Series: A 1D array, like a single column in a spreadsheet.
- DataFrame: A 2D table, like an entire Excel sheet or a SQL table. This is the heart of Pandas.
Syntax or Core Structure
Creating DataFrames
You usually import Pandas as pd.
import pandas as pd
# 1. From a Dictionary
data = {
"Name": ["Harsh", "Alice", "Bob"],
"Age": [25, 30, 22],
"Score": [88, 92, 79]
}
df = pd.DataFrame(data)
# 2. Loading from a CSV (The most common way)
# df = pd.read_csv("data.csv")
print(df.head()) # Shows the first 5 rows
Data Inspection
- df.info(): A summary of columns, null values, and data types.
- df.describe(): Statistical summary (count, mean, std, min, max, percentiles).
- df.columns: A list of all column headers.
- df.shape: Number of (rows, columns).
Code Example #1 (Basic)
Selecting data and basic filtering.
import pandas as pd
df = pd.DataFrame({
"Product": ["Laptop", "Mouse", "Keyboard", "Monitor"],
"Category": ["Electronics", "Computer", "Computer", "Electronics"],
"Price": [1200, 25, 75, 300]
})
# 1. Select a single column
prices = df["Price"]
# 2. Filter: Only products more expensive than $100
premium = df[df["Price"] > 100]
print("Premium Products:\n", premium)
Code Example #2 (Intermediate)
Grouping and cleaning data. This is where Pandas shines!
import pandas as pd
data = {
"City": ["London", "Paris", "London", "Paris", "London"],
"Sales": [5000, 4500, 7000, 3000, 1000]
}
df = pd.DataFrame(data)
# 1. Grouping: Calculate total sales by city
city_totals = df.groupby("City")["Sales"].sum()
print("City-wise Sales:\n", city_totals)
# 2. Handling Missing Data (Simulation)
df.loc[0, "Sales"] = None # Add a missing value
clean_df = df.fillna(0) # Replace NaN (Not a Number) with 0
Real World Example
Sales Data Analysis: Imagine you have a CSV file of sales. You need to find the most profitable month.
import pandas as pd
# 📊 Simple Sales Report Logic
data = {
"Month": ["Jan", "Feb", "Mar", "Apr"],
"Revenue": [10000, 15000, 12000, 18000],
"Expense": [7000, 8000, 9000, 8500]
}
df = pd.DataFrame(data)
# Calculate Profit
df["Profit"] = df["Revenue"] - df["Expense"]
# Find the maximum profit
best_month = df[df["Profit"] == df["Profit"].max()]
print("Performance Report:")
print(df)
print(f"\nBest Month: {best_month['Month'].values[0]} with ${best_month['Profit'].values[0]} profit!")
Common Mistakes
- Iterating with Loops: Beginners often try to loop through rows with a
forloop. Don't! Use "vectorized" operations likedf['Total'] = df['A'] + df['B']. It's 100x faster. - SettingWithCopyWarning: Trying to modify a slice of a DataFrame (
df[df['Score'] > 50]['Grade'] = 'A') often fails. Use.locfor safe assignment:df.loc[df['Score'] > 50, 'Grade'] = 'A'. - Forgetting Case Sensitivity: "Price" and "price" are different in Pandas. If you get a
KeyError, check your spelling and capitalization!
Best Practices
- Vectorization over Iteration: Always use built-in Pandas functions for math and logic.
- Use .loc and .iloc: Be explicit about how you are selecting data.
.locis for labels,.ilocis for integer positions. - Chaining Operations: You can chain methods like
df.dropna().groupby('City').sum(). It makes code concise and readable.
Practice Exercises
- The Employee List: Create a DataFrame with names, departments, and salaries for 5 employees. Filter to show only those in the "HR" department.
- The Statistician: Take an array of random numbers, convert it to a Pandas Series, and calculate the mean, median, and mode.
- CSV Challenge: Use
df.to_csv("my_data.csv")to save your employee DataFrame to a file, then try to read it back into a new variable usingpd.read_csv().