惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Help Net Security
Help Net Security
S
Schneier on Security
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
K
Kaspersky official blog
B
Blog
雷峰网
雷峰网
MyScale Blog
MyScale Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Latest news
Latest news
J
Java Code Geeks
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
S
Secure Thoughts
IT之家
IT之家
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
S
Security @ Cisco Blogs
罗磊的独立博客
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
P
Proofpoint News Feed
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
D
DataBreaches.Net
S
SegmentFault 最新的问题
V
Visual Studio Blog
V
V2EX
The Register - Security
The Register - Security
N
News | PayPal Newsroom
aimingoo的专栏
aimingoo的专栏
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
Hacker News: Ask HN
Hacker News: Ask HN
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
Webroot Blog
Webroot Blog
NISL@THU
NISL@THU
D
Darknet – Hacking Tools, Hacker News & Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Loading Data From Anywhere (And Why It Always Breaks the First Time)
Akhilesh · 2026-04-26 · via DEV Community

Here is a thing that happens to every data scientist at least once a week.

You download a dataset. Clean CSV file, looks straightforward. You run pd.read_csv("data.csv"). Python explodes. Error you have never seen before. The file opened fine in Excel. What happened?

Or you call an API. JSON comes back. You try to load it. The structure is three levels deep and nothing is where you expected.

Or someone sends you an .xlsx file with five sheets, merged cells, and a color-coded header that means something only they understand.

Loading data is never as simple as the documentation makes it look. This post covers the real experience. Including the parts that break and why.


CSV: Simple in Theory

A CSV file is plain text. Values separated by commas. One row per line. Should be easy.

import pandas as pd

df = pd.read_csv("students.csv")
print(df.head())

Enter fullscreen mode Exit fullscreen mode

That works about 60% of the time. The other 40%, something is off.

Problem 1: Wrong separator

Someone saved the file with semicolons instead of commas. Common in European locales where commas are used as decimal points.

df = pd.read_csv("data.csv", sep=";")

Enter fullscreen mode Exit fullscreen mode

Problem 2: Encoding errors

You see characters like é instead of é. The file was saved in a different encoding than UTF-8.

df = pd.read_csv("data.csv", encoding="latin-1")
# or try:
df = pd.read_csv("data.csv", encoding="cp1252")

Enter fullscreen mode Exit fullscreen mode

When you are not sure, try UTF-8 first. If you see garbage characters, try latin-1. That covers most cases.

Problem 3: Messy headers

df = pd.read_csv("data.csv")
print(df.columns.tolist())
# ['Name ', ' Age', 'Score ', ' Department']  <- spaces everywhere

Enter fullscreen mode Exit fullscreen mode

Fix in one line:

df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
print(df.columns.tolist())
# ['name', 'age', 'score', 'department']

Enter fullscreen mode Exit fullscreen mode

Clean column names before doing anything else. Spaces and inconsistent casing cause mysterious errors later.

Problem 4: First few rows are metadata, not headers

Some files have a title or description before the actual data starts.

df = pd.read_csv("report.csv", skiprows=3)

Enter fullscreen mode Exit fullscreen mode

Problem 5: The file is huge

Loading a 4GB CSV into memory crashes your laptop.

chunk_size = 10000
chunks = []

for chunk in pd.read_csv("huge_file.csv", chunksize=chunk_size):
    processed = chunk[chunk["value"] > 0]
    chunks.append(processed)

df = pd.concat(chunks, ignore_index=True)
print(f"Loaded {len(df)} rows after filtering")

Enter fullscreen mode Exit fullscreen mode

chunksize tells Pandas to read the file in pieces. Process each piece, keep what you need, throw away the rest. You can handle files larger than your RAM this way.


JSON: When the Structure Is a Surprise

JSON comes from APIs. It looks clean. It is structured. It is also almost never a flat table.

import json

with open("users.json", "r") as f:
    data = json.load(f)

print(type(data))
print(data[0] if isinstance(data, list) else data)

Enter fullscreen mode Exit fullscreen mode

If it is a list of dictionaries, pd.DataFrame(data) usually just works.

df = pd.DataFrame(data)
print(df.head())

Enter fullscreen mode Exit fullscreen mode

The problem is when it is not flat.

nested = {
    "results": [
        {"id": 1, "user": {"name": "Alex", "age": 25}, "score": 88},
        {"id": 2, "user": {"name": "Priya", "age": 30}, "score": 92}
    ],
    "total": 2,
    "page": 1
}

Enter fullscreen mode Exit fullscreen mode

pd.DataFrame(nested["results"]) gives you a column called user that contains dictionaries. Not what you want.

df = pd.json_normalize(nested["results"])
print(df)

Enter fullscreen mode Exit fullscreen mode

Output:

   id  score user.name  user.age
0   1     88      Alex        25
1   2     92     Priya        30

Enter fullscreen mode Exit fullscreen mode

pd.json_normalize flattens nested JSON into columns. The dot notation in column names shows the nesting depth. Clean, usable, one function call.


Excel: The Format That Contains Surprises

df = pd.read_excel("report.xlsx")

Enter fullscreen mode Exit fullscreen mode

That works for a clean single-sheet file. Real Excel files from real people are almost never that.

Multiple sheets:

all_sheets = pd.read_excel("report.xlsx", sheet_name=None)

print(all_sheets.keys())

for sheet_name, sheet_df in all_sheets.items():
    print(f"{sheet_name}: {sheet_df.shape}")

Enter fullscreen mode Exit fullscreen mode

sheet_name=None loads every sheet into a dictionary. Keys are sheet names, values are DataFrames.

Specific sheet:

df = pd.read_excel("report.xlsx", sheet_name="Q3 Sales")

Enter fullscreen mode Exit fullscreen mode

Skipping decorative rows:

Many Excel reports have a logo, title, and blank rows before the real data starts.

df = pd.read_excel("report.xlsx", skiprows=4, header=0)

Enter fullscreen mode Exit fullscreen mode

Selecting specific columns:

df = pd.read_excel("report.xlsx", usecols="A:E")     # by letter
df = pd.read_excel("report.xlsx", usecols=[0, 1, 4]) # by position

Enter fullscreen mode Exit fullscreen mode

Install openpyxl if you see an import error with xlsx files:

pip install openpyxl

Enter fullscreen mode Exit fullscreen mode


APIs: JSON You Did Not Save

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users")

print(f"Status code: {response.status_code}")
print(f"Content type: {response.headers['content-type']}")

data = response.json()
print(f"Type: {type(data)}")
print(f"Records: {len(data)}")

df = pd.json_normalize(data)
print(df[["id", "name", "email", "address.city"]].head())

Enter fullscreen mode Exit fullscreen mode

Output:

Status code: 200
Content type: application/json; charset=utf-8
Type: <class 'list'>
Records: 10
   id               name                  email address.city
0   1   Leanne Graham   Sincere@april.biz      Gwenborough
1   2   Ervin Howell    Shanna@melissa.tv      Wisokyburgh
2   3   Clementine B..  Nathan@yesenia.net     McKenziehaven

Enter fullscreen mode Exit fullscreen mode

Always check status code before processing. 200 means success. 404 means the URL is wrong. 429 means you are hitting the rate limit. 500 means their server broke.

Handle failures:

def safe_get(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        print("Request timed out")
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
    return None

Enter fullscreen mode Exit fullscreen mode

raise_for_status() throws an exception on any 4xx or 5xx response. Always use it in production code.


Useful read_csv Parameters Worth Knowing

df = pd.read_csv(
    "data.csv",
    sep=",",               # delimiter
    header=0,              # row to use as column names (0 = first row)
    index_col="id",        # use this column as row index
    usecols=["name", "age", "score"],   # only load these columns
    dtype={"age": int, "score": float}, # specify dtypes upfront
    na_values=["N/A", "null", "none", "?"],  # treat these as NaN
    parse_dates=["date_column"],         # parse as datetime
    nrows=1000,            # only load first 1000 rows
    skiprows=[1, 2],       # skip specific rows
    encoding="utf-8",
    low_memory=False       # prevents mixed dtype warnings on large files
)

Enter fullscreen mode Exit fullscreen mode

You will not use all of these every time. But when a file misbehaves, one of these usually fixes it.


Checking What You Loaded

Never assume your file loaded correctly. Always verify.

def inspect_dataframe(df, name="DataFrame"):
    print(f"\n{'='*50}")
    print(f"{name}")
    print(f"{'='*50}")
    print(f"Shape: {df.shape}")
    print(f"\nColumn dtypes:")
    print(df.dtypes)
    print(f"\nMissing values:")
    print(df.isnull().sum())
    print(f"\nFirst 3 rows:")
    print(df.head(3))
    print(f"\nBasic stats:")
    print(df.describe())

df = pd.read_csv("students.csv")
inspect_dataframe(df, "Students Dataset")

Enter fullscreen mode Exit fullscreen mode

Run this every time you load a new file. It takes five seconds and saves you from building analysis on corrupted or misloaded data.


A Blog Worth Reading on This

Towards Data Science has a well-known post by Parul Pandey titled "A Beginner's Guide to Pandas" that covers real-world data loading patterns and common mistakes with great examples. Search "Parul Pandey pandas beginner guide towards data science" and it comes right up.

Will Koehrsen wrote a piece called "Pandas Tricks" on Towards Data Science that goes into depth on efficient data loading and the edge cases with CSV files. One of the most bookmarked posts in the data science community. Search "Will Koehrsen pandas tricks".

Both are worth reading alongside this post. Not instead of practicing the code, but as companions.


Try This

Create loading_practice.py.

Part one: download any CSV dataset from Kaggle (the Titanic dataset or the Iris dataset are perfect starters, both are free and tiny).

Load it and run the inspect_dataframe function above. Fix any column name issues with .str.strip().str.lower(). Print the missing value counts and decide what to do with them.

Part two: call this free API that returns a list of countries with their populations and regions.

https://restcountries.com/v3.1/all?fields=name,population,region,subregion

Enter fullscreen mode Exit fullscreen mode

Use requests.get. Parse the JSON. Turn it into a DataFrame. The name field is itself a nested dict with a "common" key. Use pd.json_normalize and then print the first 10 rows with name, population, and region visible.

Sort by population descending. Print the top 10 most populated countries.


What's Next

You can load data now. But data from the real world is almost never clean. Next post is entirely about dirty data: missing values, wrong types, duplicate rows, impossible values. How to find all of it systematically and what to do about each kind.