What is Pandas Analysis?
Pandas analysis means using the Pandas library to inspect, transform, summarize, compare, and understand structured data. It is commonly used for sales analysis, customer analysis, employee reports, financial analysis, inventory management, and many other business tasks.
DataFrame
A two-dimensional table containing rows and columns.
Filtering
Select only the records that satisfy specific conditions.
Grouping
Divide data into groups and calculate summaries for each group.
Aggregation
Calculate totals, averages, counts, minimums, maximums, and more.
Pandas is usually installed using pip.
pip install pandas
Import Pandas using the common alias pd.
import pandas as pd
Suppose an online store wants to analyze its monthly sales. We can create a DataFrame representing order records.
import pandas as pd
data = {
"OrderID": [1001, 1002, 1003, 1004, 1005, 1006],
"Product": ["Laptop", "Phone", "Laptop", "Headphones", "Phone", "Tablet"],
"Category": ["Electronics", "Electronics", "Electronics",
"Accessories", "Electronics", "Electronics"],
"City": ["Pune", "Mumbai", "Pune", "Delhi", "Mumbai", "Pune"],
"Quantity": [2, 3, 1, 5, 2, 4],
"Price": [60000, 30000, 60000, 3000, 30000, 25000]
}
df = pd.DataFrame(data)
print(df)
View the First Rows
print(df.head())
View the Last Rows
print(df.tail())
Check Number of Rows and Columns
print(df.shape)
(6, 6)
Use info() to understand column names,
data types, and missing values.
df.info()
You can also inspect individual data types.
print(df.dtypes)
Selecting columns allows you to focus on the information needed for a particular analysis.
print(df["Product"])
print(df[["Product", "Quantity", "Price"]])
A common analysis task is calculating the total value of every order.
df["Sales"] = df["Quantity"] * df["Price"]
print(df[["OrderID", "Product", "Quantity", "Price", "Sales"]])
Total Sales
total_sales = df["Sales"].sum()
print("Total Sales:", total_sales)
Average Sales
average_sales = df["Sales"].mean()
print("Average Sales:", average_sales)
Maximum and Minimum Sales
print("Maximum:", df["Sales"].max())
print("Minimum:", df["Sales"].min())
The describe() function provides statistical
information such as count, mean, standard deviation,
minimum, maximum, and quartiles.
print(df.describe())
Filtering helps answer questions such as: "Which orders generated more than ₹50,000?"
high_value_orders = df[df["Sales"] > 50000]
print(high_value_orders)
Another example is finding all orders from Pune.
pune_orders = df[df["City"] == "Pune"]
print(pune_orders)
Use & for AND conditions and
| for OR conditions.
result = df[
(df["City"] == "Pune") &
(df["Sales"] > 50000)
]
print(result)
result = df[
(df["City"] == "Pune") |
(df["City"] == "Mumbai")
]
print(result)
Sorting is useful when identifying the highest-selling products or customers.
sorted_df = df.sort_values(
by="Sales",
ascending=False
)
print(sorted_df)
value_counts() helps understand how frequently
each category appears.
print(df["Product"].value_counts())
print(df["City"].value_counts())
groupby() is one of the most important Pandas
tools for business analysis.
Total Sales by City
city_sales = df.groupby("City")["Sales"].sum()
print(city_sales)
Total Sales by Product
product_sales = df.groupby("Product")["Sales"].sum()
print(product_sales)
You can calculate multiple statistics for each group.
summary = df.groupby("Product").agg(
Total_Sales=("Sales", "sum"),
Average_Sales=("Sales", "mean"),
Total_Quantity=("Quantity", "sum"),
Number_of_Orders=("OrderID", "count")
)
print(summary)
product_sales = df.groupby("Product")["Sales"].sum()
best_product = product_sales.idxmax()
best_sales = product_sales.max()
print("Best Product:", best_product)
print("Sales:", best_sales)
idxmax() returns the label associated with the
largest value.
product_sales = df.groupby("Product")["Sales"].sum()
lowest_product = product_sales.idxmin()
lowest_sales = product_sales.min()
print("Lowest Product:", lowest_product)
print("Sales:", lowest_sales)
Revenue alone does not tell the complete story. A product may have high revenue because of a high price, while another product may sell many more units.
quantity_by_product = df.groupby("Product")["Quantity"].sum()
print(quantity_by_product)
city_analysis = df.groupby("City").agg(
Total_Sales=("Sales", "sum"),
Total_Quantity=("Quantity", "sum"),
Orders=("OrderID", "count")
)
print(city_analysis)
Businesses often want to know what percentage of total revenue comes from each product.
product_sales = df.groupby("Product")["Sales"].sum()
sales_percentage = (
product_sales / product_sales.sum()
) * 100
print(sales_percentage)
Average Order Value, or AOV, is a common e-commerce metric.
aov = df["Sales"].mean()
print("Average Order Value:", aov)
You can create additional columns to support analysis.
df["Cost"] = df["Sales"] * 0.70
df["Profit"] = df["Sales"] - df["Cost"]
print(df[["Product", "Sales", "Cost", "Profit"]])
profit_by_product = df.groupby("Product")["Profit"].sum()
print(profit_by_product)
Missing values can affect analysis results, so they should be checked before calculating important metrics.
print(df.isnull().sum())
Fill Numeric Missing Values
df["Price"] = df["Price"].fillna(
df["Price"].mean()
)
Remove Rows with Missing Values
df = df.dropna()
df = df.drop_duplicates()
print(df)
This is useful when the same transaction has accidentally been loaded more than once.
Real business analysis usually starts with files rather than manually created DataFrames.
df = pd.read_csv("sales.csv")
print(df.head())
df = pd.read_excel("sales.xlsx")
print(df.head())
An e-commerce company wants to identify customers who have spent more than ₹100,000.
customer_data = {
"Customer": ["Amit", "Priya", "Rahul", "Sneha", "Vikas"],
"Orders": [8, 12, 5, 15, 10],
"TotalSpent": [75000, 145000, 45000, 180000, 120000]
}
customers = pd.DataFrame(customer_data)
high_value_customers = customers[
customers["TotalSpent"] > 100000
]
print(high_value_customers)
employees = pd.DataFrame({
"Name": ["Amit", "Priya", "Rahul", "Sneha", "Vikas"],
"Department": [
"IT", "HR", "IT", "Finance", "IT"
],
"Salary": [
65000, 55000, 80000, 72000, 90000
]
})
department_salary = employees.groupby(
"Department"
)["Salary"].agg(["mean", "min", "max"])
print(department_salary)
A warehouse needs to identify products that are running low.
inventory = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet", "Monitor", "Mouse"],
"Stock": [25, 8, 40, 6, 75],
"ReorderLevel": [10, 15, 15, 10, 20]
})
low_stock = inventory[
inventory["Stock"] < inventory["ReorderLevel"]
]
print(low_stock)
students = pd.DataFrame({
"Student": ["A", "B", "C", "D", "E"],
"Math": [85, 72, 91, 65, 78],
"Science": [88, 75, 89, 70, 82],
"English": [80, 78, 92, 68, 85]
})
students["Average"] = students[
["Math", "Science", "English"]
].mean(axis=1)
print(students)
Find students with an average score above 80.
top_students = students[
students["Average"] > 80
]
print(top_students)
monthly_sales = pd.DataFrame({
"Month": [
"January", "February", "March",
"April", "May", "June"
],
"Sales": [
120000, 145000, 132000,
168000, 175000, 190000
]
})
monthly_sales["Growth"] = (
monthly_sales["Sales"].pct_change() * 100
)
print(monthly_sales)
pct_change() helps measure percentage change
between consecutive periods.
Growth analysis helps determine whether business performance is increasing or decreasing over time.
first_month = monthly_sales["Sales"].iloc[0]
last_month = monthly_sales["Sales"].iloc[-1]
growth = (
(last_month - first_month) / first_month
) * 100
print("Overall Growth:", growth, "%")
nlargest() can quickly identify the highest
values.
top_orders = df.nlargest(
3,
"Sales"
)
print(top_orders)
Similarly, nsmallest() can find the lowest values.
lowest_orders = df.nsmallest(
3,
"Sales"
)
print(lowest_orders)
You can compare categories using grouped statistics.
category_analysis = df.groupby("Category").agg(
Revenue=("Sales", "sum"),
Units=("Quantity", "sum"),
Orders=("OrderID", "count")
)
print(category_analysis)
Pivot tables summarize data across multiple dimensions.
pivot = pd.pivot_table(
df,
values="Sales",
index="City",
columns="Product",
aggfunc="sum",
fill_value=0
)
print(pivot)
Concatenating Data
january = pd.DataFrame({
"Product": ["Laptop", "Phone"],
"Sales": [120000, 90000]
})
february = pd.DataFrame({
"Product": ["Laptop", "Phone"],
"Sales": [140000, 110000]
})
combined = pd.concat(
[january, february],
ignore_index=True
)
print(combined)
In real applications, customer information and order information may be stored in separate tables.
customers = pd.DataFrame({
"CustomerID": [1, 2, 3],
"CustomerName": ["Amit", "Priya", "Rahul"]
})
orders = pd.DataFrame({
"CustomerID": [1, 2, 1, 3],
"Sales": [50000, 75000, 30000, 90000]
})
merged = pd.merge(
customers,
orders,
on="CustomerID",
how="inner"
)
print(merged)
customer_revenue = merged.groupby(
"CustomerName"
)["Sales"].sum()
print(customer_revenue)
The following example combines several Pandas analysis techniques into one workflow.
import pandas as pd
sales = pd.DataFrame({
"OrderID": [1, 2, 3, 4, 5, 6, 7, 8],
"Product": [
"Laptop", "Phone", "Laptop", "Tablet",
"Phone", "Laptop", "Tablet", "Phone"
],
"City": [
"Pune", "Mumbai", "Delhi", "Pune",
"Mumbai", "Delhi", "Pune", "Delhi"
],
"Quantity": [2, 3, 1, 4, 2, 1, 5, 3],
"Price": [
60000, 30000, 60000, 25000,
30000, 60000, 25000, 30000
]
})
# Calculate revenue
sales["Revenue"] = (
sales["Quantity"] * sales["Price"]
)
# Total revenue
total_revenue = sales["Revenue"].sum()
# Revenue by product
product_revenue = sales.groupby(
"Product"
)["Revenue"].sum()
# Revenue by city
city_revenue = sales.groupby(
"City"
)["Revenue"].sum()
# Top orders
top_orders = sales.nlargest(
3,
"Revenue"
)
print("Total Revenue:")
print(total_revenue)
print("\nRevenue by Product:")
print(product_revenue)
print("\nRevenue by City:")
print(city_revenue)
print("\nTop Orders:")
print(top_orders)
A summary DataFrame can combine important business metrics.
summary = pd.DataFrame({
"Metric": [
"Total Orders",
"Total Revenue",
"Average Order Value",
"Maximum Order"
],
"Value": [
len(df),
df["Sales"].sum(),
df["Sales"].mean(),
df["Sales"].max()
]
})
print(summary)
Save to CSV
summary.to_csv(
"sales_analysis.csv",
index=False
)
Save to Excel
summary.to_excel(
"sales_analysis.xlsx",
index=False
)
| Function | Purpose | Example |
|---|---|---|
head() |
View first rows | df.head() |
info() |
Inspect dataset | df.info() |
describe() |
Statistical summary | df.describe() |
sum() |
Calculate total | df["Sales"].sum() |
mean() |
Calculate average | df["Sales"].mean() |
count() |
Count records | df["OrderID"].count() |
groupby() |
Group records | df.groupby("City") |
sort_values() |
Sort records | df.sort_values("Sales") |
value_counts() |
Count categories | df["City"].value_counts() |
nlargest() |
Find highest values | df.nlargest(5, "Sales") |
nsmallest() |
Find lowest values | df.nsmallest(5, "Sales") |
pivot_table() |
Create summaries | pd.pivot_table(...) |
- Inspect the dataset before performing calculations.
- Check for missing and duplicate values.
- Verify column data types.
- Use meaningful column names.
- Create calculated columns for important business metrics.
- Use
groupby()for category-level analysis. - Use filtering to answer specific business questions.
- Validate totals before publishing reports.
- Keep raw data separate from transformed data.
- Export important analysis results for reporting.
Imagine an e-commerce company receives thousands of orders every day. A Pandas analysis workflow could look like this:
import pandas as pd
# 1. Load data
df = pd.read_csv("orders.csv")
# 2. Inspect data
print(df.head())
print(df.info())
# 3. Remove duplicate records
df = df.drop_duplicates()
# 4. Handle missing values
df["Quantity"] = df["Quantity"].fillna(0)
df["Price"] = df["Price"].fillna(df["Price"].mean())
# 5. Calculate revenue
df["Revenue"] = df["Quantity"] * df["Price"]
# 6. Total revenue
total_revenue = df["Revenue"].sum()
# 7. Product analysis
product_analysis = df.groupby("Product").agg(
Revenue=("Revenue", "sum"),
Units=("Quantity", "sum"),
Orders=("OrderID", "count")
)
# 8. City analysis
city_analysis = df.groupby("City")["Revenue"].sum()
# 9. Top orders
top_orders = df.nlargest(10, "Revenue")
# 10. Save results
product_analysis.to_csv(
"product_analysis.csv"
)
city_analysis.to_csv(
"city_analysis.csv"
)
print("Total Revenue:", total_revenue)
print(product_analysis)
print(city_analysis)
print(top_orders)
- Pandas DataFrames are commonly used for structured data analysis.
- Always inspect the data before analyzing it.
- Use
describe()for a quick statistical overview. - Use Boolean filtering to select relevant records.
- Use
groupby()to summarize categories. -
Use aggregation functions such as
sum(),mean(),count(),min(), andmax(). - Use
sort_values()to identify high and low values. - Use
pivot_table()for multi-dimensional summaries. - Check for missing values and duplicates before important calculations.
- Validate analysis results against the original data.
- Keep raw data separate from cleaned and analyzed data.
- Document important assumptions used in calculations.
- Export final results when they need to be shared or reported.
Python Pandas Analysis • Real-Time Examples • Data Analysis Learning