
Quick answer: Pandas is the most popular Python library for data analysis. Its two main structures are the Series (one column) and the DataFrame (a table of rows and columns). With Pandas you can read CSV and Excel files, select and filter rows, add calculated columns, group and summarise data, handle missing values and plot results with Matplotlib. Install it with pip install pandas and import it as pd.
All code examples were run on Python 3.13 with Pandas 3.0; the outputs shown are real.
Contents
- Create a DataFrame
- Read and Write CSV or Excel Files
- Select and Filter Data
- Add Calculated Columns and Sort
- Summary Statistics with describe()
- Group and Summarise with groupby()
- Handle Missing Values
- Plot Data with Matplotlib
- Common Pandas Functions Cheat Sheet
Create a DataFrame
import pandas as pd
data = {"material": ["Steel", "Aluminium", "Titanium"],
"E_GPa": [200, 69, 116],
"density": [7850, 2700, 4500]}
df = pd.DataFrame(data)
print(df)Output:
material E_GPa density 0 Steel 200 7850 1 Aluminium 69 2700 2 Titanium 116 4500
Read and Write CSV or Excel Files
Most real data comes from files:
import pandas as pd
df = pd.read_csv("test_results.csv") # or pd.read_excel("data.xlsx")
print(df.head()) # first 5 rows
df.to_csv("cleaned_results.csv", index=False)
Reading Excel files needs the openpyxl package (pip install openpyxl).
Select and Filter Data
Select a column with df[“col”], filter rows with a condition, and pick cells with loc (by label) or iloc (by position).
import pandas as pd
df = pd.DataFrame({"material": ["Steel", "Aluminium", "Titanium"], "E_GPa": [200, 69, 116], "density": [7850, 2700, 4500]})
print(df["E_GPa"].tolist())
print(df[df["density"] < 5000]["material"].tolist())
print(df.loc[0, "material"], df.iloc[2, 1])Output:
[200, 69, 116] ['Aluminium', 'Titanium'] Steel 116
Add Calculated Columns and Sort
Specific stiffness (E/ρ) is a key value when choosing lightweight materials:
import pandas as pd
df = pd.DataFrame({"material": ["Steel", "Aluminium", "Titanium"], "E_GPa": [200, 69, 116], "density": [7850, 2700, 4500]})
df["specific_stiffness"] = (df["E_GPa"] * 1e9 / df["density"] / 1e6).round(2)
print(df.sort_values("specific_stiffness", ascending=False)[["material", "specific_stiffness"]])Output:
material specific_stiffness 2 Titanium 25.78 1 Aluminium 25.56 0 Steel 25.48
Summary Statistics with describe()
import pandas as pd
s = pd.Series([72, 85, 64, 91, 78])
print(s.describe().round(2))Output:
count 5.00 mean 78.00 std 10.61 min 64.00 25% 72.00 50% 78.00 75% 85.00 max 91.00 dtype: float64
Group and Summarise with groupby()
import pandas as pd
df = pd.DataFrame({"branch": ["Mech", "Aero", "Mech", "Aero", "Mech"],
"marks": [78, 85, 66, 90, 72]})
print(df.groupby("branch")["marks"].mean())Output:
branch Aero 87.5 Mech 72.0 Name: marks, dtype: float64
Handle Missing Values
isna() finds missing values, fillna() replaces them and dropna() removes incomplete rows.
import pandas as pd
import numpy as np
df = pd.DataFrame({"load": [100, np.nan, 300], "deflection": [0.2, 0.4, np.nan]})
print(df.isna().sum().tolist())
print(df.fillna(0).values.tolist())
print(len(df.dropna()))Output:
[1, 1] [[100.0, 0.2], [0.0, 0.4], [300.0, 0.0]] 1
Plot Data with Matplotlib
Pandas works directly with Matplotlib to make report-ready graphs:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"load_N": [0, 500, 1000, 1500, 2000],
"deflection_mm": [0, 0.42, 0.83, 1.25, 1.67]})
plt.plot(df["load_N"], df["deflection_mm"], marker="o")
plt.xlabel("Load (N)")
plt.ylabel("Deflection (mm)")
plt.title("Load vs Deflection")
plt.grid(True)
plt.savefig("load_deflection.png", dpi=200)
plt.show()
This saves a high-resolution graph you can insert into a project report or paper.
Common Pandas Functions Cheat Sheet
| Task | Code |
|---|---|
| First rows | df.head() |
| Rows and columns | df.shape |
| Column types | df.info() |
| Rename columns | df.rename(columns={"a": "b"}) |
| Drop a column | df.drop(columns=["col"]) |
| Unique values | df["col"].unique() |
| Count values | df["col"].value_counts() |
| Merge tables | pd.merge(df1, df2, on="id") |
Frequently Asked Questions
What is Pandas used for in Python?
Pandas is used for data analysis – reading CSV and Excel files, cleaning data, filtering rows, adding calculated columns, grouping and summarising, and preparing data for plots and machine learning.
What is the difference between a Series and a DataFrame?
A Series is a single labelled column of data; a DataFrame is a two-dimensional table made of multiple Series sharing the same index.
What is the difference between loc and iloc?
loc selects by row and column labels; iloc selects by integer positions.
Is Pandas built on NumPy?
Yes. Pandas uses NumPy arrays internally, so NumPy functions work on Pandas columns.
How can engineers use Pandas?
Engineers use Pandas to process test data, sensor logs and simulation results, compare design cases, calculate derived values and create graphs for reports.
Related Python Guides
- NumPy tutorial
- Python programs with output
- Python for mechanical engineers
- Python interview questions
- All Python tutorials
Learn Python With Guidance
Join our Python course or message us on WhatsApp for doubt-clearing and project support.