0% found this document useful (0 votes)
4 views10 pages

Python DataAnalysis Guide

This document serves as a comprehensive learning guide for Year 1 engineering students at Chulalongkorn University, focusing on Python and data analysis. It outlines a structured roadmap with four phases, covering Python fundamentals, data libraries, data analysis techniques, and basic machine learning concepts, along with practical exercises and projects. Additionally, it provides curated free resources for further learning in Python and data analysis relevant to engineering applications.

Uploaded by

gearnattapol1152
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Python DataAnalysis Guide

This document serves as a comprehensive learning guide for Year 1 engineering students at Chulalongkorn University, focusing on Python and data analysis. It outlines a structured roadmap with four phases, covering Python fundamentals, data libraries, data analysis techniques, and basic machine learning concepts, along with practical exercises and projects. Additionally, it provides curated free resources for further learning in Python and data analysis relevant to engineering applications.

Uploaded by

gearnattapol1152
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python &

Data Analysis
Complete Learning Guide for Engineering Students

Faculty of Engineering Chulalongkorn University


Target Audience Year 1 Stude

4 5 4 10+
Learning Code Exercises Free
Phases Examples & Projects Resources

Table of Contents
01 Learning Roadmap — 4 phases from zero to Data Analysis

02 Python Fundamentals — Variables, Loops, Functions

03 Data Libraries — NumPy, Pandas, Matplotlib

04 Code Examples — 5 annotated examples with engineering context

05 Exercises & Projects — 4 hands-on exercises for engineers

06 Free Learning Resources — Curated list of best free courses & tools

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 1
01 LEARNING ROADMAP — From Zero to Data Analysis

This roadmap is designed specifically for Chulalongkorn Engineering students who have no programming background.
Each phase builds on the previous one. Spending 30-60 minutes per day, you can complete all 4 phases within one
semester.

Python Fundamentals 4-6 Weeks


P1

Variables & Data Types (int, float, str, bool, list, dict)
Conditional Statements: if / elif / else
Loops: for loop, while loop, range()
Functions: def, parameters, return values
File I/O: reading and writing .txt and .csv files

GOAL: Write a program to calculate GPA and find max/min from a list of scores

Data Libraries 4-6 Weeks


P2

NumPy: array operations, mathematical calculations


Pandas: DataFrame, read CSV/Excel, filter, sort, groupby
Matplotlib: line plot, bar chart, histogram, scatter plot
Seaborn: statistical visualization, heatmaps

GOAL: Import an Excel file, filter data, and create a chart in 10 lines of code

Data Analysis 6-8 Weeks


P3

Exploratory Data Analysis (EDA): shape, info, describe()


Handling missing values: fillna(), dropna()
Statistical analysis: mean, std, correlation matrix
Dashboard building with Plotly / Streamlit
Full project: analyze real engineering dataset end-to-end

GOAL: Build an interactive dashboard analyzing machinery sensor data from a CSV file

Machine Learning Basics 8+ Weeks


P4

Scikit-learn: Linear Regression, Classification


Train/Test split and cross-validation
Evaluation metrics: accuracy, RMSE, confusion matrix
Predictive Maintenance for mechanical systems
Feature engineering for engineering data

GOAL: Build a model to predict remaining useful life of machine components

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 2
PRO TIP
Start with Google Colab ([Link]) — it runs Python in your browser with zero installation. Just open a new notebook
and start typing. Perfect for Phase 1 and 2.

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 3
02 PYTHON FUNDAMENTALS — Core Concepts with Engineering Context

Example 1: Variables & Data Types


Python does not require declaring variable types — it figures them out automatically. This makes it ideal for quick
engineering calculations and prototyping.

example_01_variables.py

# Variables — no type declaration needed


component_name = "Piston Rod" # string
diameter_mm = 45.5 # float
cycle_count = 10000 # integer
is_critical = True # boolean

# F-string formatting (recommended in Python 3.6+)


print(f"Component : {component_name}")
print(f"Diameter : {diameter_mm} mm")
print(f"Cycles : {cycle_count:,}")

# List — store multiple values


temperatures = [82.1, 91.4, 78.3, 95.0, 88.6]
print(f"First reading : {temperatures[0]}")
print(f"Last reading : {temperatures[-1]}")
print(f"Total points : {len(temperatures)}")

# Dictionary — key:value pairs (like a data record)


sensor = {
"id" : "SENSOR-007",
"unit" : "Celsius",
"max" : 120.0
}
print(f"Sensor ID: {sensor["id"]} Max: {sensor["max"]}C")

Example 2: Loops & Conditionals


Loops allow you to process lists of data automatically — essential for analyzing sensor readings, material properties, or
test results.

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 4
example_02_loops.py

# Process 24-hour temperature log automatically


hourly_temps = [28,27,26,25,24,25,28,32,38,45,52,58,
61,63,61,57,50,44,38,35,32,31,29,28]
THRESHOLD = 60 # degrees Celsius — danger zone

# for loop — iterate over each item


overheated_hours = []
for i, temp in enumerate(hourly_temps):
if temp >= THRESHOLD:
overheated_hours.append(i)
print(f" ALERT Hour {i:02d}: {temp}C >= {THRESHOLD}C")

# Summary statistics using loop


total = 0
for t in hourly_temps:
total = total + t
average = total / len(hourly_temps)

print(f"Average : {average:.1f}C")
print(f"Max : {max(hourly_temps)}C")
print(f"Overheated hours: {len(overheated_hours)}")

# List Comprehension — Pythonic one-liner


high = [t for t in hourly_temps if t > THRESHOLD]
print(f"Danger readings: {high}")

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 5
03 FUNCTIONS & DATA LIBRARIES

Example 3: Functions — Reusable Engineering Calculations


Functions package repeated logic into named blocks you can call any time. This is how real engineering software is
structured.

example_03_functions.py

# Engineering calculation functions


def calculate_stress(force_N, area_mm2):
"""Calculate normal stress sigma = F/A (MPa)"""
if area_mm2 <= 0:
raise ValueError("Area must be positive")
return round(force_N / area_mm2, 3)

def safety_factor(yield_strength, applied_stress):


"""SF = yield_strength / applied_stress"""
if applied_stress == 0:
return float("inf")
return round(yield_strength / applied_stress, 2)

def analyze_batch(forces, area):


"""Analyze multiple force readings at once"""
stresses = [calculate_stress(f, area) for f in forces]
return {
"mean_MPa" : round(sum(stresses)/len(stresses), 3),
"max_MPa" : max(stresses),
"min_MPa" : min(stresses),
"count" : len(stresses)
}

# Usage
forces = [15000, 18500, 12000, 21000, 16800] # Newtons
AREA = 314.16 # mm^2 (10mm radius circle)
YIELD = 250 # MPa (structural steel)

results = analyze_batch(forces, AREA)


print(f"Mean stress : {results["mean_MPa"]} MPa")
print(f"Safety factor (mean): {safety_factor(YIELD, results["mean_MPa"])}")

Example 4: Pandas — Table Data Analysis


Pandas turns Python into a supercharged Excel. A DataFrame is a table with rows and columns — you can filter,
calculate, and visualize millions of rows in seconds.

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 6
example_04_pandas.py

import pandas as pd

# Create DataFrame (like an Excel sheet in Python)


data = {
"Subject" : ["Calculus","Physics","Chemistry","Drawing","Programming"],
"Credits" : [3, 3, 3, 2, 3],
"Score" : [85, 78, 92, 88, 95],
}
df = [Link](data)

# Basic inspection
print([Link]) # (5, 3) — 5 rows, 3 columns
print([Link]()) # count, mean, std, min, max

# Filtering rows
high_scores = df[df["Score"] >= 90]
print(high_scores)

# Adding a calculated column


df["Grade"] = df["Score"].apply(
lambda s: "A" if s>=90 else "B+" if s>=80 else "B"
)

# Weighted GPA calculation


df["WeightedScore"] = df["Score"] * df["Credits"]
gpa_score = df["WeightedScore"].sum() / df["Credits"].sum()
print(f"Weighted Average: {gpa_score:.2f}")

# Read real CSV file (one line!)


# df = pd.read_csv("sensor_data.csv")

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 7
04 EXERCISES & PROJECTS — Practice with Engineering Data

These exercises are designed for mechanical and petroleum engineering students. Each one uses a realistic
engineering scenario. Complete them in Google Colab.

Exercise 01 GPA Calculator (No Built-ins) Beginner

Create a list of 6 subject scores and their credits. Without using sum(), max(), or min() built-in functions, write a
program to calculate: (1) weighted average, (2) highest scoring subject, (3) lowest scoring subject, (4) number of
subjects with score >= 80.

hint_exercise_01.py

scores = [85, 72, 91, 68, 79, 88]


credits = [3, 3, 3, 2, 3, 1]
# Hint: use a for loop to accumulate total
total_weighted = 0
total_credits = 0
for s, c in zip(scores, credits):
total_weighted += s * c
total_credits += c
gpa = total_weighted / total_credits

Exercise 02 Machinery Temperature Analyzer Intermediate

Given 24 hourly temperature readings of an engine, write a function analyze_engine(temps, threshold) that returns: (1)
number of hours above threshold, (2) average temperature during those hours, (3) the hour index when temperature
first exceeded the threshold.

hint_exercise_02.py

def analyze_engine(temps, threshold):


high_hours = [(i, t) for i, t in enumerate(temps)
if t > threshold]
if not high_hours:
return 0, None, None
first_idx = high_hours[0][0]
avg_high = sum(t for _, t in high_hours) / len(high_hours)
return len(high_hours), round(avg_high, 1), first_idx

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 8
Exercise 03 Pandas: Analyze Equipment Dataset Intermediate

Download the "Machine Predictive Maintenance Classification" dataset from Kaggle (free, 10,000 rows). Using
Pandas: (1) load the CSV, (2) check for missing values, (3) find average torque per machine type, (4) plot a histogram
of rotational speed, (5) identify top 5 rows with highest tool wear.

hint_exercise_03.py

import pandas as pd
import [Link] as plt

df = pd.read_csv("predictive_maintenance.csv")
print([Link]().sum()) # check missing
print([Link]("Type")["Torque [Nm]"].mean())
df["Rotational speed [rpm]"].hist(bins=30)
[Link]("Rotational Speed Distribution")
[Link]()
print([Link](5, "Tool wear [min]"))

Exercise 04 Mini Project: Engineering Data Dashboard Advanced

FINAL PROJECT: Choose a dataset related to your target major (mechanical: machinery/automotive, petroleum: oil
well/reservoir data). Perform a complete EDA: (1) load & clean data, (2) generate 3 different chart types, (3) find top 3
most correlated variables, (4) write a 5-sentence summary of your findings in comments.

hint_exercise_04.py

# Suggested datasets on Kaggle:


# Mechanical: "Steel Industry Energy Consumption"
# Mechanical: "CNC Mill Tool Wear"
# Petroleum : "Oil Well Production Data"
# Petroleum : "Crude Oil Price Historical Data"

import pandas as pd
import seaborn as sns
import [Link] as plt

df = pd.read_csv("your_dataset.csv")
print([Link]().abs().unstack().sort_values()[-10:])

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 9
05 FREE LEARNING RESOURCES — Curated for Engineering Students

START HERE — Python Basics (Free)

5 hours | Learn in browser | Get certificate


Kaggle — Python Course [Link]/learn/python | Exercises included

Full university course | Excellent


exercises | Highly recommended for
Harvard CS50P [Link]/python serious learners

Free cloud Jupyter notebook | No


installation | Free GPU | Start coding in
Google Colab [Link] 30 seconds

Data Analysis Libraries

4 hours | Hands-on with real datasets |


Certificate | Best Pandas course for
Kaggle — Pandas Course [Link]/learn/pandas beginners

4 hours | Seaborn & Matplotlib | Real


Kaggle — Data Visualization [Link]/learn/data-visualization chart-making practice

In-depth tutorials | Engineering


applications | Free articles + premium
Real Python [Link] courses

Machine Learning (Phase 4)

3 hours | Scikit-learn | Decision trees,


Kaggle — Intro to ML [Link]/learn/intro-to-machine-learning Random Forest | Certificate

Free deep learning course | Top-down


approach | Used by industry
[Link] [Link] professionals

Engineering Datasets (Free)

Search: "machine failure", "oil


production", "CNC tool wear", "steel
Kaggle Datasets [Link]/datasets industry"

Classic industrial & engineering datasets |


UCI ML Repository [Link] Well-documented | Free download

Thai government open data | Energy,


[Link] [Link] environment, infrastructure datasets

1. Start today — open Google Colab and type your first line of P
on weekends. Consistency is everything. 3. Build real projects —
actually care about. 4. Use AI tools (ChatGPT, Claude) to explai
Year 2, you will be the person your classmates ask for help with

Python & Data Analysis for Engineering Students | Chulalongkorn University Page 10

You might also like