跳到正文 Applied Week 1 · Jimmy Huang's Blog
← Week 1 Introduction to Data Wrangling 学习 › C6001 › 2026 S1 › FIT5196 Data wrangling › Week 1 Introduction to Data Wrangling Applied Week 1 Applied Week 1 本页目录· 60 条 ChatGPT 说 › Overview 本周的 Applied / Practical 重点不是做一个很大的项目,而是先把后面课程会一直用到的基础工作流搭起来。
一方面,你要先熟悉 Jupyter Notebook 的基本使用方式,知道 kernel、cell、Markdown、code cell、快捷键 分别是什么,能在 notebook 里写说明、跑代码、展示输出;另一方面,你还要完成一个 AI Practical 小任务:借助 AI 生成并理解一段 Python 代码,从公共 API 抓取 JSON 数据,整理成结构化结果,打印成表格,并写出到 CSV 文件。
这周真正的主线有两条:
会用 notebook :后面很多实验、报告、作业都会在 notebook 里完成,所以这周要先把 Markdown、代码单元、输出展示、基础快捷键练熟。
会解释代码 :不仅要把代码跑起来,还要知道每一段在干什么
Goal 这周实验完成后,你应该能够:
打开并使用 Jupyter Notebook 或 Google Colab
区分 Markdown cell 和 Code cell
使用 Markdown 写基本标题、列表、链接、表格
读懂并运行简单的 Python 代码、 for loop 和 function
自己完成一个 transpose_matrix 函数
使用 AI 辅助完成一个 API → JSON → structured data → table → CSV 的小任务
能解释 requests
本页目录 、
logging
、
dataclass
、
Path
、
tabulate
这些模块在代码里的作用
Task 0: 环境准备与打开 Notebook
Step 0.1:选择运行环境
方案 A:本地 Python + Jupyter Notebook 安装本周会用到的核心库,并启动 Jupyter Notebook。
后面所有操作都要在 notebook 环境里完成;如果缺库,运行示例代码和 AI Practical 代码时会直接报错。
浏览器打开 Jupyter 页面后,能看到文件列表,且可以新建或打开 .ipynb 文件。
方案 B:Anaconda 如果你平时用的是 Anaconda,也可以直接在 Anaconda Prompt 中安装:
方案 C:Google Colab 如果你不想本地安装 Python,可以直接使用 Google Colab:
打开 Google Colab
登录账号
上传老师提供的 notebook,或者新建 notebook
后续所有代码都在 Colab 里运行
Step 0.2:打开本周需要的两个 Notebook
Step 0.3:先熟悉最基本的 notebook 操作 先把 notebook 的“操作方式”练熟,不然后面你会经常卡在“为什么不能编辑 / 为什么不能运行 / 为什么不是 Markdown”。
Jupyter Notebook 有 command mode 和 edit mode 两套操作逻辑,不先搞清楚会非常容易误操作。
Task 1: 完成 Markdown 练习与个人小结 这一部分对应老师 notebook 里的 Task 1
你需要用 Markdown 写一个简短总结,说明自己过去的数据分析经历
老师原始要求包括:数据简介、遇到的挑战、如何处理、学到了什么
这部分不需要编造复杂内容,但一定要是你自己的经历
做完后,你应该能把一段原始文本整理成结构清楚的 Markdown 内容
Step 1.1:先理解这部分到底要交什么 简要介绍你过去处理过的数据
说明数据处理时遇到的挑战 / 数据问题
说明你用什么方法处理这些问题
说明你从这段经历里学到了什么
这不是让你写学术报告,而是让你练习如何在 notebook 里用 Markdown 做简洁说明。
Step 1.2:新建一个 Markdown cell,并填入下面这个模板 老师要看的核心不是英文有多华丽,而是你有没有用 Markdown 把信息写清楚。
如果你之前没有正式做过数据分析,也可以写课程、小项目、作业、Excel 整理数据的经历。
点击该 Markdown cell,然后按 Shift + Enter,确认它被渲染成格式化文本,而不是原始标记符号。
Step 1.3:顺手练一下最常用的 Markdown 语法 下面这些语法是后面做 notebook 报告最常用的:
标题(headings)
无序列表(bullet points)
有序列表(numbered list)
链接(links)
表格(tables) 把 notebook 报告里最常见的 Markdown 结构先练一遍。
后面课程里,你很可能要在 notebook 中同时写文字说明、放代码、贴图、放表格;这些基础语法以后会反复用到。
Task 2: 运行基础 Python 示例,并完成 transpose_matrix
Step 2.1:先运行一个最简单的代码 cell 运行后,代码 cell 左侧的执行编号会变化,例如从 [] 变成 [1]、 [2] 等。
Step 2.2:运行一个简单绘图示例 演示 notebook 不只是能输出文本,还能直接显示图表。
Jupyter Notebook 在后面数据分析课程里最重要的价值之一,就是可以把“代码 + 图 + 说明”放在同一个文档里。
Step 2.3:运行 for loop 示例,熟悉循环结构
示例 1:遍历列表
示例 2:遍历字符串
示例 3:遍历数字范围
示例 4:嵌套循环(nested loops) 依次练习最常见的循环写法:遍历列表、字符串、数字区间,以及双层循环。
后面的 transpose_matrix 本质上就要用到 nested loops 的思路。
for item in sequence 是“从一个可迭代对象里逐个取值”
range(5) 会生成 0, 1, 2, 3, 4
双层循环常用于二维结构,比如表格、矩阵
Step 2.4:定义并调用一个函数 练习 Python function 的基本结构: def、参数、函数体、调用。
后面的 transpose_matrix 不是零散代码,而是要封装成一个函数。
Step 2.5:完成矩阵转置函数 transpose_matrix原矩阵是按“行(row)”存放数据, transpose 之后会把“行”和“列(column)”交换位置。
完成老师 notebook 里的核心 Python 小任务。
function 定义
nested loops
二维数据结构的行列转换
Task 3: 完成 AI Practical —— 从 API 抓数据并导出 CSV 这一部分对应 AI_Practical_Demo_Tutorial_student.ipynb
官方要求是:借助 AI 完成一个 Python 任务,而不是完全手写
核心流程是: 请求 API → 解析 JSON → 抽取字段 → 组织成结构化数据 → 表格展示 → 写入 CSV
Step 3.1:先打开一个 AI 工具,并把任务说清楚 ChatGPT
Claude
Cursor
GitHub Copilot Chat
Google Colab 内置 AI
把需求一次性说完整,减少 AI 第一次回答偏题的概率。
这个任务要求很多细节:API、环境变量、异常处理、结构化数据、表格、CSV、路径、类型提示。
Step 3.2:如果 notebook 缺库,先安装依赖
本地终端安装
如果你在 Colab / Notebook 里直接装 最常见的第一类报错就是 ModuleNotFoundError,先把库装好能节省很多时间。
本周要求里“从环境变量读取 API URL”是推荐做法。
即使你没有真的使用 .env 文件,只要代码里写了 os.getenv("API_URL", 默认地址),也已经满足“有默认 fallback”这个要求。
安装成功后,再运行 import requests、 from tabulate import tabulate 不应报错。
Step 3.3:生成第一版代码后,对照下面这份参考解答补齐 如果你的 AI 第一版已经满足要求,可以直接使用自己的版本。
如果 AI 第一版不完整、漏掉了某些模块,或者你想快速核对结构,可以参考下面这份完整版本。
把 AI Practical 的核心任务一次性完成。
API_URL = os.getenv(...)先从环境变量读取 API 地址;如果你没有设置环境变量,就用默认值 https://jsonplaceholder.typicode.com/users。
UserRow
fetch_users()如果失败,不会让整个程序直接崩掉,而是记录错误并返回空列表。
transform_users()address["city"]
company["name"]
display_users()使用 tabulate 把结果以表格形式打印出来,方便在 notebook 中直接查看。
write_csv()创建 output 目录,并把同样的数据写到 output/users.csv。
Step 3.4:运行并检查结果 Notebook 中有表格输出
日志里出现类似 “Fetched N users” 和 “CSV written to …” 的信息
当前工作目录下出现 output/users.csv
Task 4: Study time、整理理解点并保存 AI 对话记录 这一部分对应 AI Practical notebook 的 Part 2、Part 3、Part 4
重点不是再写新代码,而是回头把已经生成的代码读懂
此外,还要把你的 AI 使用过程留档,方便后续复盘或作业记录
做完后,你应该能简洁解释自己的代码,并保留一份 AI 对话记录
Step 4.1:按模块回读自己的 AI 代码 requestsGET 请求是怎么发的
timeout 为什么重要
raise_for_status() 在做什么
.json() 返回什么类型的数据
csv + PathCSV 是怎么写出去的
为什么先 mkdir 再写文件
后续 assessment、presentation、Q&A 都会看你是否真正理解自己的方案,而不是只会复制 AI 生成的代码。
Step 4.2:保存 AI 对话记录
如果你用的是 Cursor
如果你用的是 ChatGPT
如果你用的是 Claude / Copilot / 其他工具
Summary 这周表面上是在做一些很基础的 notebook 和 Python 练习,但真正要建立的是后面整个学期都会反复用到的工作方式:
用 notebook 组织实验过程 不只是写代码,还要把说明、输出、图表、结果一起放进一个文档里。
把代码拆开理解,而不是只会运行 这周的 transpose_matrix 和 AI Practical 都在练这个能力:看到代码时,知道每一层循环、每个函数、每个模块分别在做什么。
把原始数据整理成可分析的结构 AI Practical 的主线就是一个很典型的数据处理流程:
获取数据 → 提取字段 → 结构化 → 展示 → 导出
学会把 AI 当成辅助工具,而不是黑盒 AI 可以帮你更快生成第一版代码,但你仍然必须自己读懂、验证、修改,并保留使用记录。
本周必须理解的知识点 Kernel 是真正执行代码的计算引擎;cell 只是承载内容的单元
Markdown cell 用来写说明, Code cell 用来运行代码
Shift + Enter 是 notebook 里最核心的运行操作
for loop 是遍历数据的基础,nested loops 常用于二维结构
transpose_matrix 的本质是把行列互换
requests 用于请求 API, .json() 用于把响应转成 Python 数据结构
dataclass 可以让每一行数据更清楚、更好管理
logging 适合记录状态与错误, print 更适合展示结果
Path 可以更稳妥地处理文件路径与目录创建
生成式 AI 可以辅助写代码,但你必须自己理解和验证
老师可能会问什么
1. 什么是 Jupyter Notebook 的 kernel? kernel 是 notebook 背后真正执行代码的运行环境。你写在 code cell 里的 Python,不是 cell 自己执行的,而是由 kernel 来执行。
2. Markdown cell 和 Code cell 有什么区别? Markdown cell 用来写说明、标题、列表、表格等文档内容;Code cell 用来运行 Python 代码并产生输出。
3. 为什么 Shift + Enter 很重要? 因为它会执行当前 cell,并通常跳到下一个 cell,是 notebook 里最常用的操作。
4. transpose_matrix 为什么要用双层循环? 因为矩阵是二维结构。外层循环按列走,内层循环按行取值,这样才能把原来每一列收集成新矩阵的一行。
5. 为什么 API 请求要设置 timeout? 避免请求因为网络问题一直卡住。设置 timeout 后,如果超时会尽快抛出异常并进入错误处理逻辑。
6. response.json() 返回的是什么? 它会把接口返回的 JSON 数据解析成 Python 数据结构,通常是 list 或 dict。
7. 为什么要用 .get() 读取 address 和 company? 因为这些字段可能缺失。直接用 user["address"]["city"] 容易在字段不存在时报错,用 .get() 更安全。
8. 为什么这里用 logging 而不是只用 print? 因为 logging 更适合记录成功、警告、错误等不同级别的信息,代码可维护性更好,也更接近真实项目写法。
9. Path.mkdir(parents=True, exist_ok=True) 在做什么? 它会在写 CSV 前确保输出目录存在;如果目录不存在就创建,如果已经存在也不会报错。
10. AI 已经把代码写出来了,为什么还要自己读懂? 因为老师检查的是你的理解,不是 AI 的能力。你需要能解释代码逻辑、验证结果、发现问题并做修改。
Write a Python solution for a Jupyter Notebook.
Task:
Fetch JSON from https://jsonplaceholder.typicode.com/users using requests.
Use an environment variable API_URL with a default fallback.
Set a timeout.
If the request fails, log a clear error and exit gracefully.
Define a dataclass or NamedTuple for one user row with:
id, name, email, city, company
Extract city from address and company name from company.
Handle missing nested fields safely.
Display the result as a formatted table using tabulate.
Use logging instead of print for success and error messages.
Write the same data to output/users.csv using csv and pathlib.Path.
Create the parent directory if needed.
Use type hints.
Do not use pandas.python -m pip install notebook matplotlib numpy requests tabulate python-dotenv conda install notebook matplotlib numpy requests tabulate python-dotenv -y import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.show() fruits = [ " apple " , " banana " , " cherry " ] for fruit in fruits: print(fruit) word = " hello " for char in word: print(char) for i in range(5): print(i) for i in range(1, 6): for j in range(1, 6): print(i * j, end= " \t " ) print() def greet(name): """ This function greets the person whose name is passed as an argument. """ print( f"Hello, {name} ! Welcome to Python programming." ) greet( " Alice " ) greet( " James " ) [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] [ [1, 4, 7], [2, 5, 8], [3, 6, 9] ] def transpose_matrix(matrix): """ This function takes a matrix (a list of lists) and returns its transpose. """ if not matrix or not matrix[0]: return [] rows = len(matrix) cols = len(matrix[0]) transpose = [] for col in range(cols): new_row = [] for row in range(rows): new_row.append(matrix[row][col]) transpose.append(new_row) return transpose matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transposed_matrix = transpose_matrix(matrix) print( " Original Matrix: " ) for row in matrix: print(row) print( " \nTransposed Matrix: " ) for row in transposed_matrix: print(row) Original Matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9] Transposed Matrix: [1, 4, 7] [2, 5, 8] [3, 6, 9] python -m pip install requests tabulate python-dotenv !pip install requests tabulate python-dotenv import csv import logging import os from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional import requests from tabulate import tabulate logging.basicConfig(level=logging.INFO, format= " %(levelname)s:%(message)s " ) API_URL = os.getenv( " API_URL " , " https://jsonplaceholder.typicode.com/users " ) OUTPUT_FILE = Path( " output/users.csv " ) @dataclass class UserRow: id: Optional[int] name: str email: str city: str company: str def fetch_users(url: str, timeout: int = 10) -> List[Dict[str, Any]]: try : response = requests.get(url, timeout=timeout) response.raise_for_status() data = response.json() logging.info( " Fetched%s users " , len(data)) return data except requests.RequestException as exc: logging.error( " Request failed:%s " , exc) return [] def transform_users(raw_users: List[Dict[str, Any]]) -> List[UserRow]: rows: List[UserRow] = [] for user in raw_users: address = user.get( " address " ) or {} company = user.get( " company " ) or {} rows.append( UserRow( id=user.get( " id " ), name=user.get( " name " , "" ), email=user.get( " email " , "" ), city=address.get( " city " , " N/A " ), company=company.get( " name " , " N/A " ), ) ) return rows def display_users(rows: List[UserRow]) -> None: table = [ [row.id, row.name, row.email, row.city, row.company] for row in rows ] print( tabulate( table, headers=[ " id " , " name " , " email " , " city " , " company " ], tablefmt= " github " ) ) def write_csv(rows: List[UserRow], output_file: Path) -> None: output_file.parent.mkdir(parents=True, exist_ok=True) with output_file.open( " w " , newline= "" , encoding= " utf-8 " ) as csvfile: writer = csv.writer(csvfile) writer.writerow([ " id " , " name " , " email " , " city " , " company " ]) for row in rows: writer.writerow([row.id, row.name, row.email, row.city, row.company]) logging.info( " CSV written to%s " , output_file.resolve()) def main() -> None: raw_users = fetch_users(API_URL) if not raw_users: logging.warning( " No data fetched. Skip display and CSV writing. " ) return rows = transform_users(raw_users) display_users(rows) write_csv(rows, OUTPUT_FILE) main() ## My past experience with data analysis ### 1. Brief introduction I previously worked with [数据类型,例如 sales data / survey data / website logs / student records]. ### 2. Challenges / data issues -The data had [missing values / duplicated records / inconsistent formats / noisy text / outliers]. -Some fields were difficult to analyse because [ 原因 ]. ### 3. How I handled the challenges -I used [Excel / Python / Pandas / SQL / manual checking] to clean the data. -I removed or fixed [duplicates / missing values / formatting issues]. -I reorganised the dataset so it was easier to analyse. ### 4. What I learned -I learned that data cleaning is essential before analysis. -I also learned that even simple data can become hard to use if the format is inconsistent. -This experience helped me understand the importance of structured and reproducible analysis. # Heading level 1 ## Heading level 2 ### Heading level 3 #### Heading level 4 ##### Heading level 5 -Bread -white bread -wholemeal bread -Milk -Cheese 1.First item 2.Second item 3.Third item [ Markdown Guide ](https://www.markdownguide.org/basic-syntax/) | Column 1 | Column 2 | Column 3 | | -------- | -------- | -------- | | value 1 | value 2 | value 3 | | value 4 | value 5 | value 6 |