Sitemap
Rohithnag

Rohithnag

Python Pandas Library

6 min readOct 3, 2026

Pandas is one of the most important Python libraries for data manipulation, data cleaning, analysis, and preparation.

It provides two primary data structures:

• Series — one-dimensional labeled data

• DataFrame — two-dimensional tabular data

Pandas is widely used in Data Analytics, Data Science, Machine Learning, and Exploratory Data Analysis because it makes structured data easier to inspect, transform, validate, and analyze.

1. Installing and Importing Pandas

Pandas can be installed using:

pip install pandas

It is generally imported using the alias pd. NumPy is often used alongside Pandas.

import pandas as pd
import numpy as np

2. Pandas Data Structures

Pandas mainly works with two data structures: Series and DataFrame.

Series

A Series is a one-dimensional labeled array.

marks = pd.Series([75, 82, 91, 68, 88])
print(marks)

The left side represents the index, while the right side contains the values. A Series can also have custom indexes.

marks = pd.Series(
[75, 82, 91],
index=["Rahul", "Amit", "Sanjay"]
)
marks["Amit"]

DataFrame

A DataFrame is a two-dimensional labeled data structure consisting of rows and columns.

data = {
"name": ["Amit", "Rahul", "Sanjay", "Priya"],
"age": [21, 22, 23, 21],
"salary": [35000, 42000, 50000, 38000]
}
df = pd.DataFrame(data)
print(df)

Rows represent observations or records. Columns represent variables or features.

3. Understanding a Dataset Before performing analysis, the first step is to understand the structure and quality of the dataset.

Reading common file formats

df = pd.read_csv("data.csv")
df = pd.read_excel("data.xlsx")
df = pd.read_json("data.json")
df = pd.read_sql(query, connection)

The same DataFrame workflow can then be applied regardless of whether the data originated from CSV, Excel, JSON, or SQL.

4. Inspecting the Dataset

head() and tail()

df.head()
df.head(10)
df.tail()

head() displays the first five rows by default, while tail() displays the last five.

shape, columns, index and dtypes

df.shape
df.columns
df.index
df.dtypes

shape returns the number of rows and columns. For example, (1000, 8) means 1000 rows and 8 columns.

info()

df.info()

info() provides a compact summary containing the number of rows, column names, non-null values, data types, and memory usage.

describe()

df.describe() 

For numerical columns describe() commonly reports count, mean, standard deviation, minimum, quartiles, and maximum.

5. Selecting Columns and Rows

Selecting columns

df[“salary”] 
df[[“name”, “age”, “salary”]]

df[“salary”] returns a Series, while df[[“salary”]] returns a DataFrame.

.loc[] — label-based indexing

df.loc[0, “name”] 
df.loc[0:2]
df.loc[:, [“name”, “salary”]]
df.loc[0:2, [“name”, “salary”]]

.iloc[] — integer-position-based indexing

df.iloc[0, 1] 
df.iloc[0:3]
df.iloc[0:3, 0:2]

A useful rule: loc → Label; iloc → Position.

6. Conditional Filtering

Filtering is one of the most important operations in Pandas.

AND condition

df[ 
(df[“salary”] > 40000) &
(df[“age”] > 21)
]

OR condition

df[
(df["salary"] > 40000) |
(df["age"] > 21)
]

NOT condition

df[~(df[“age”] > 21)]

Filtering and selecting columns together

df.loc[
df[“salary”] > 40000,
[“name”, “salary”]
]

7. Unique Values and Frequencies

unique() and nunique()

df[“gender”].unique() 
df[“gender”].nunique()

unique() returns distinct values, while nunique() returns the number of distinct values.

value_counts()

df[“gender”].value_counts() 
df[“gender”].value_counts(normalize=True) * 100

value_counts() is especially useful for categorical analysis because it shows the frequency of each value and can also return percentages.

8. Missing Values

Missing values are commonly represented by NaN, None, or NaT.

df.isnull() 
df.isnull().sum()
df.isnull().mean() * 100
df.isna().sum()

Removing missing values

df.dropna() 
df.dropna(subset=[“salary”])
df.dropna(axis=1)

Missing values should not automatically be deleted. The correct treatment depends on the amount of missing data, variable type, reason for missingness, and business context.

Get Rohithnag’s stories in your inbox

Join Medium for free to get updates from this writer.

Filling missing values

df[“age”] = df[“age”].fillna(df[“age”].mean())
df[“salary”] = df[“salary”].fillna(df[“salary”].median())
df[“gender”] = df[“gender”].fillna(df[“gender”].mode()[0])
df[“salary”] = df[“salary”].ffill()
df[“salary”] = df[“salary”].bfill()

For machine-learning workflows, missing-value treatment should be fitted using training data only when appropriate, so validation or test information does not leak into model training.

9. Duplicate Values

df.duplicated() 
df.duplicated().sum()
df = df.drop_duplicates()
df.drop_duplicates(subset=[“email”])

Checking duplicates is an important part of data validation. Duplicate rows may inflate counts, averages, or other statistics.

10. Changing Data Types

df.dtypes 
df[“age”] = df[“age”].astype(int)
df[“salary”] = df[“salary”].astype(float)
df[“name”] = df[“name”].astype(str)
df[“date”] = pd.to_datetime(df[“date”])

Correct data types make filtering, calculations, comparisons, and date operations more reliable.

11. String Operations

Pandas provides the .str accessor for vectorized string operations.

df[“name”].str.lower() 
df[“name”].str.upper()
df[“name”].str.strip()
df[“name”].str.contains(“Amit”, na=False)
df[“name”].str.replace(“Amit”, “Rahul”)
df[“name”].str[:3]

These operations are useful for standardizing names, categories, IDs, email fields, and other text columns.

12. Sorting and Creating Columns Sorting

df.sort_values(“salary”) 
df.sort_values(“salary”, ascending=False)
df.sort_values([“age”, “salary”], ascending=[True, False])

Adding a new column

df[“annual_salary”] = df[“monthly_salary”] * 12 
df[“status”] = df[“salary”].apply(
lambda x: “High” if x > 50000 else “Low”
)

Vectorized alternative

df[“status”] = np.where( 
df[“salary”] > 50000,
“High”,
“Low”
)

13. Updating and Transforming Values

Updating values with a condition

df.loc[df[“age”] > 30, “category”] = “Senior” 

Replacing specific values

df[“gender”] = df[“gender”].replace({ 
“M”: “Male”,
“F”: “Female”
})

apply()

df[“salary”].apply(lambda x: x * 12) 
def salary_category(salary):
if salary >= 50000:
return “High”
return “Low”
df[“category”] = df[“salary”].apply(salary_category)

When a vectorized Pandas or NumPy operation can perform the same task, it is often preferable because it can be more efficient.

map()

gender_map = {“M”: 0, “F”: 1} 
df[“gender_encoded”] = df[“gender”].map(gender_map)

14. GroupBy and Aggregation

groupby() is one of the most important Pandas operations for data analysis. It follows the idea of Split → Apply → Combine.

df.groupby(“department”)[“salary”].mean() 

df.groupby(“department”)[“salary”].agg(
[“mean”, “min”, “max”, “count”]
)
df.groupby([“department”, “gender”])[“salary”].mean()

Common aggregation functions

df[“salary”].sum() 
df[“salary”].mean()
df[“salary”].median()
df[“salary”].min()
df[“salary”].max()
df[“salary”].count()
df[“salary”].std()
df[“salary”].var()

Named aggregation

df.groupby(“department”).agg( 
average_salary=(“salary”, “mean”),
maximum_salary=(“salary”, “max”),
employee_count=(“salary”, “count”)
)

15. Pivot Tables and Crosstabs

pivot_table()

A pivot table summarizes data based on one or more categorical variables.

pd.pivot_table( 
df,
values=”salary”,
index=”department”,
columns=”gender”,
aggfunc=”mean”
)

crosstab()

pd.crosstab(df[“gender”], df[“department”]) 
pd.crosstab(
df[“gender”],
df[“department”],
normalize=”index”
) * 100

crosstab() is particularly useful for frequency tables involving categorical variables.

16. Finding Maximum and Minimum Records

df[“salary”].idxmax() 
df[“salary”].idxmin()
df.loc[df[“salary”].idxmax()]

idxmax() and idxmin() return the index associated with the maximum or minimum value. The corresponding row can then be retrieved with loc[].

17. Combining DataFrames

Pandas provides concat(), merge(), and join() for combining datasets.

concat()

result = pd.concat([df1, df2], axis=0) 
result = pd.concat([df1, df2], axis=1)

merge()

result = pd.merge( 
customers,
orders,
on=”customer_id”,
how=”inner”
)
Press enter or click to view image in full size

18. Date and Time Operations

df[“date”] = pd.to_datetime(df[“date”]) 
df[“year”] = df[“date”].dt.year
df[“month”] = df[“date”].dt.month
df[“day”] = df[“date”].dt.day
df[“weekday”] = df[“date”].dt.day_name()

Datetime features are useful for time-series analysis, monthly reporting, trend analysis, and event-based filtering.

19. Numerical Operations

df[“salary”].sum() 
df[“salary”].mean()
df[“salary”].median()
df[“salary”].std()
df[“salary”].var()
df[“salary”].min()
df[“salary”].max()
df[“salary”].abs()
df[“salary”].round(2)

Pandas provides direct numerical operations on Series and DataFrames, often allowing analysis without explicit Python loops.

20. Handling Potential Outliers

The IQR method is commonly used for identifying potential outliers.

Q1 = df["salary"].quantile(0.25) 
Q3 = df["salary"].quantile(0.75)
IQR = Q3 - Q1
lower_limit = Q1 - 1.5 * IQR
upper_limit = Q3 + 1.5 * IQR
outliers = df[
(df["salary"] < lower_limit) |
(df["salary"] > upper_limit)
]
df_clean = df[
(df["salary"] >= lower_limit) &
(df["salary"] <= upper_limit)]

An outlier should not automatically be deleted. It may represent a data-entry error, a genuine extreme observation, a rare event, or an important business case. Treatment should depend on context.

21. Important Pandas Methods — Cheat Sheet

Press enter or click to view image in full size

22. Final Summary

Pandas is not simply a library for reading CSV files. It provides a practical framework for working with structured data from the first inspection through cleaning, transformation, analysis, and reporting.

Python
↓
Pandas
↓
Series & DataFrame
↓
Data Selection
↓
loc / iloc
↓
Filtering
↓
Missing Values
↓
Duplicates
↓
Data Types
↓
String & Date Operations
↓
Sorting & Transformation
↓
GroupBy & Aggregation

↓
Pivot Table & Crosstab
↓
Merge & Concatenation
↓
Outlier Analysis
↓
Exploratory Data Analysis
↓
Visualization
↓
Insights
↓
Machine Learning / Data Science

The most important principle when working with Pandas is:

Do not begin analysis before understanding the data.

A strong Pandas workflow starts with inspection, continues through cleaning and transformation, and ends with analysis and interpretation. Once these operations become familiar, Pandas becomes a foundation for practical Exploratory Data Analysis and for preparing datasets for statistical analysis and Machine Learning.

End of Article

upper_limit = Q3 + 1.5 * IQR outliers = df[ (df[“salary”] upper_limit) ] df_clean = df[ (df[“salary”] >= lower_limit) & (df[“salary”]

--

--