What Is Data Collection? 📥Data Collection क्या है? 📥什么是数据收集?📥
Data collection is the planned process of gathering raw information so it can be stored, cleaned and analysed. It is the first stage of every data science project — and often the most important. However powerful your model, your results can only be as good as the data you collected.
Data collection, कच्ची जानकारी को योजना के साथ जुटाने की प्रक्रिया है, ताकि उसे रखा, साफ़ किया और analyse किया जा सके। यह हर data science project का पहला चरण है — और अक्सर सबसे ज़रूरी। आपका model कितना भी ताक़तवर हो, नतीजे उतने ही अच्छे होंगे जितना अच्छा data आपने जुटाया।
数据收集是有计划地获取原始信息,以便存储、清洗和分析的过程。它是每个数据科学项目的第一步 —— 往往也是最重要的一步。模型再强大,结果也只能和你收集的数据一样好。
A model trained on badly collected or biased data gives bad, biased predictions — even if every later step is perfect. Cleaning can fix typos and missing values, but it cannot recover people who were never asked or events that were never recorded.
ख़राब तरीके से जुटाए या biased data पर train हुआ model ख़राब, biased predictions देता है — भले ही बाद का हर step सही हो। Cleaning टाइपो और missing values ठीक कर सकती है, पर उन लोगों को वापस नहीं ला सकती जिनसे कभी पूछा ही नहीं गया, या वे घटनाएँ जो कभी दर्ज नहीं हुईं।
用收集不当或有偏的数据训练的模型,即使后续每一步都完美,也会给出糟糕、有偏的预测。数据清洗能修正错别字和缺失值,却找不回从未被询问的人或从未被记录的事件。
Primary vs Secondary Data 🧭Primary बनाम Secondary Data 🧭一手数据 vs 二手数据 🧭
Before choosing a tool, decide whether you will collect new data yourself (primary) or reuse data someone else collected (secondary). Most projects mix both.
Tool चुनने से पहले तय करें कि आप नया data ख़ुद जुटाएँगे (primary) या किसी और का जुटाया data इस्तेमाल करेंगे (secondary)। ज़्यादातर projects दोनों मिलाते हैं।
选工具之前,先决定是自己收集新数据(一手)还是复用别人收集的数据(二手)。大多数项目两者兼用。
| Typeप्रकार类型 | How it is collectedकैसे जुटाया जाता है收集方式 | Strengthताक़त优点 | Watch out forसावधानी注意 |
|---|---|---|---|
| PrimaryPrimary一手 | Surveys, experiments and A/B tests, sensors and IoT devices, app and website logsSurveys, experiments और A/B tests, sensors और IoT devices, app और website logs问卷调查、实验与 A/B 测试、传感器与物联网设备、应用和网站日志 | You control what is measured and howक्या और कैसे मापा जाए, यह आपके हाथ में测什么、怎么测由你掌控 | Cost, time, consent and privacyख़र्च, समय, सहमति और privacy成本、时间、知情同意与隐私 |
| SecondarySecondary二手 | Company databases, public APIs, government portals, open datasets, published researchCompany databases, public APIs, सरकारी portals, open datasets, प्रकाशित research公司数据库、公开 API、政府门户、开放数据集、已发表研究 | Fast and cheap; often largeतेज़ और सस्ता; अक्सर बड़ा快速便宜,往往规模大 | It was collected for another purpose — check definitions, gaps, licence and ageकिसी और मक़सद से जुटाया गया — परिभाषाएँ, कमियाँ, licence और पुरानापन जाँचें它是为其他目的收集的 —— 要检查定义、缺口、许可和时效 |
Source 1 — Databases 🗄️Source 1 — Databases 🗄️来源 1 — 数据库 🗄️
Databases are the most common source inside companies. Sales, users, payments and logs usually live in relational tables queried with SQL (Structured Query Language). There are two main families:
Companies के अंदर databases सबसे आम source हैं। Sales, users, payments और logs आम तौर पर relational tables में रहते हैं जिन्हें SQL (Structured Query Language) से query किया जाता है। दो मुख्य परिवार हैं:
数据库是公司内部最常见的数据来源。销售、用户、支付和日志通常存放在关系型表中,用 SQL(结构化查询语言)查询。主要有两大类:
Writing "... WHERE name = '" + user_input + "'" invites SQL injection, where a crafted input changes your query. Always pass values separately as parameters (? or %s placeholders). It is also faster to filter and aggregate inside the database than to download everything and filter in pandas.
"... WHERE name = '" + user_input + "'" लिखना SQL injection को न्योता देता है, जहाँ कोई ख़ास input आपकी query बदल देता है। Values हमेशा parameters की तरह अलग से दें (? या %s placeholders)। सब कुछ download करके pandas में filter करने से database के अंदर filter और aggregate करना तेज़ भी है।
写成 "... WHERE name = '" + user_input + "'" 会招来 SQL 注入:精心构造的输入会改变你的查询。始终把值作为参数单独传入(? 或 %s 占位符)。而且在数据库内部完成过滤和聚合,比全部下载后再用 pandas 过滤更快。
Source 2 — APIs 🔌Source 2 — APIs 🔌来源 2 — API 🔌
An API (Application Programming Interface) lets your code ask another service for data over the internet. The service replies — usually in JSON, sometimes XML — and your code parses and stores the reply.
API (Application Programming Interface) आपके code को internet पर किसी दूसरी service से data माँगने देता है। Service जवाब देती है — आम तौर पर JSON में, कभी-कभी XML में — और आपका code उसे parse करके रखता है।
API(应用程序编程接口)让你的代码通过互联网向另一个服务请求数据。服务返回响应 —— 通常是 JSON,有时是 XML —— 你的代码解析并保存它。
| APIAPIAPI | DataData数据 | Key neededKey चाहिए需要密钥 | Cost (check current terms)ख़र्च (मौजूदा शर्तें देखें)费用(以最新条款为准) |
|---|---|---|---|
| X (Twitter) API | Posts, users, trendsPosts, users, trends帖子、用户、趋势 | Yesहाँ需要 | Paid (pay-per-use for new developers since 2026)Paid (2026 से नए developers के लिए pay-per-use)付费(2026 年起新开发者按量计费) |
| OpenWeatherMap | Temperature, humidity, forecastsतापमान, नमी, forecasts气温、湿度、预报 | Yesहाँ需要 | Free tierFree tier有免费层 |
| Alpha Vantage | Stock prices, financialsStock prices, financials股价、财务数据 | Yesहाँ需要 | Small free daily quotaछोटा free daily quota每日免费额度很小 |
| NASA Open APIs | Space and Earth imageryअंतरिक्ष और पृथ्वी की तस्वीरें太空与地球影像 | Yes (demo key for testing)हाँ (testing के लिए demo key)需要(可用演示密钥测试) | FreeFree免费 |
| REST Countries | Country facts, flagsदेशों की जानकारी, झंडे国家信息、国旗 | Noनहीं不需要 | FreeFree免费 |
Pick a scenario and send. Watch the request travel, the status code come back, and — for a good reply — the JSON turn into a table. "Too many requests" fires 8 calls at a server that allows only 3 per 2 seconds.
एक स्थिति चुनें और भेजें। Request को जाते, status code को लौटते, और — सही जवाब पर — JSON को table बनते देखें। "बहुत ज़्यादा requests" ऐसे server पर 8 calls भेजता है जो हर 2 सेकंड में सिर्फ़ 3 देता है।
选择一个场景并发送。观察请求发出、状态码返回,以及(成功时)JSON 变成表格。“请求过多”会向一个每 2 秒只允许 3 次请求的服务器连发 8 次。
Most APIs limit requests per minute or per day. Pause between calls, and when you get a 429, wait and retry with exponential backoff (1 s, 2 s, 4 s, … plus a little random jitter). If the reply includes a Retry-After header, use that wait time. Cache results so you never download the same thing twice.
ज़्यादातर APIs हर मिनट या हर दिन requests सीमित करते हैं। Calls के बीच रुकें, और 429 मिलने पर exponential backoff से इंतज़ार करके दोबारा कोशिश करें (1 s, 2 s, 4 s, … थोड़े random jitter के साथ)। अगर जवाब में Retry-After header हो तो वही इंतज़ार समय लें। नतीजे cache करें ताकि एक ही चीज़ दो बार download न हो।
大多数 API 会限制每分钟或每天的请求数。调用之间要停顿;收到 429 时,用指数退避等待后重试(1 秒、2 秒、4 秒……再加一点随机抖动)。如果响应带有 Retry-After 头,就按它给出的时间等待。缓存结果,避免重复下载同样的数据。
Source 3 — Flat Files (CSV, Excel, JSON, Parquet) 📄Source 3 — Flat Files (CSV, Excel, JSON, Parquet) 📄来源 3 — 平面文件(CSV、Excel、JSON、Parquet)📄
Files are the simplest and most universal way to share data. Clients, government portals and researchers often send data as file dumps.
Files, data share करने का सबसे सरल और सबसे आम तरीका हैं। Clients, सरकारी portals और researchers अक्सर data files के रूप में भेजते हैं।
文件是共享数据最简单、最通用的方式。客户、政府门户和研究人员常常以文件形式提供数据。
| FormatFormat格式 | Best forसबसे अच्छा最适合 | PythonPythonPython | Notesनोट्स说明 |
|---|---|---|---|
| .csv | Tables; universal exchangeTables; हर जगह चलता है表格;通用交换 | pandas.read_csv | Human-readable; no data types; slow when largeपढ़ने में आसान; data types नहीं; बड़ा हो तो धीमा人可读;不存类型;大文件较慢 |
| .xlsx | Business reportsBusiness reports业务报表 | pandas.read_excel (openpyxl)pandas.read_excel (openpyxl)pandas.read_excel(openpyxl) | Several sheets; watch merged cells and hidden rowsकई sheets; merged cells और छिपी rows पर ध्यान多工作表;注意合并单元格和隐藏行 |
| .json | Nested data, API repliesNested data, API जवाब嵌套数据、API 响应 | json / pandas | Flexible but verboseलचीला पर लंबा灵活但冗长 |
| .parquet | Large analytical dataबड़ा analytical data大型分析数据 | pandas + pyarrowpandas + pyarrowpandas + pyarrow | Columnar, compressed, keeps typesColumnar, compressed, types रखता है列式存储、压缩、保留类型 |
| .xml | Older systems, some government dataपुराने systems, कुछ सरकारी data老系统、部分政府数据 | lxml / xml.etree | Verbose tree of tagsTags का लंबा tree冗长的标签树 |
Parquet stores data column by column, so a query that needs one column reads only that column. It also compresses well and remembers data types. In our test below, a 1-million-row table was 23 MB as CSV and 10 MB as Parquet, and reading one column was about 5× faster. Gains vary with the data; with wide tables they are often much larger. Parquet is a standard format in Spark, Databricks and cloud data lakes.
Parquet data column दर column रखता है, इसलिए एक column वाली query सिर्फ़ वही column पढ़ती है। यह अच्छा compress भी करता है और data types याद रखता है। नीचे के हमारे test में 10 लाख rows वाली table CSV में 23 MB और Parquet में 10 MB थी, और एक column पढ़ना लगभग 5× तेज़ था। फ़ायदा data के साथ बदलता है; चौड़ी tables में यह अक्सर कहीं ज़्यादा होता है। Parquet, Spark, Databricks और cloud data lakes का standard format है।
Parquet 按列存储数据,所以只需一列的查询就只读那一列。它压缩效果好,还保留数据类型。在下面的测试中,100 万行的表存成 CSV 为 23 MB,存成 Parquet 为 10 MB,读取一列快了约 5 倍。收益随数据而变;对于很宽的表,往往大得多。Parquet 是 Spark、Databricks 和云数据湖中的标准格式。
The same small table is stored two ways. Pick a query and run it. Count how many cells each format has to read.
वही छोटी table दो तरह से रखी है। एक query चुनें और चलाएँ। गिनें कि हर format को कितने cells पढ़ने पड़ते हैं।
同一张小表用两种方式存储。选一个查询并运行,数一数每种格式需要读取多少个单元格。
Source 4 — Web Scraping 🕸️Source 4 — Web Scraping 🕸️来源 4 — 网页抓取 🕸️
When a website shows data but offers no API, you can write code that downloads the page's HTML and pulls out the parts you need. This is web scraping.
जब website data दिखाती है पर कोई API नहीं देती, तो आप ऐसा code लिख सकते हैं जो page का HTML download करे और ज़रूरी हिस्से निकाले। यही web scraping है।
当网站展示了数据却没有提供 API 时,你可以写代码下载页面的 HTML 并提取所需部分。这就是网页抓取。
This is a made-up shop page. Click a selector to see which parts of the page and the HTML it matches. Then extract the table.
यह एक काल्पनिक दुकान का page है। Selector पर click करें और देखें कि page और HTML के कौन-से हिस्से मेल खाते हैं। फिर table निकालें।
这是一个虚构的书店页面。点击选择器,看它匹配页面和 HTML 的哪些部分,然后提取表格。
robots.txt tells bots which pages the site owner does not want crawled; respect it even where it is not legally binding. Scraping personal data, copyrighted content, or breaking a site's terms of service can have legal consequences, and the rules differ by country. Do not overload servers, identify your scraper honestly, and prefer official APIs or downloads whenever they exist.
robots.txt bots को बताता है कि site का मालिक किन pages को crawl नहीं करवाना चाहता; जहाँ यह क़ानूनी रूप से बाध्य न हो वहाँ भी इसका सम्मान करें। निजी data, copyright वाली सामग्री scrape करना, या site की terms of service तोड़ना क़ानूनी नतीजे ला सकता है, और नियम देश के हिसाब से बदलते हैं। Servers पर बोझ न डालें, अपने scraper की सही पहचान दें, और official APIs या downloads हों तो उन्हें प्राथमिकता दें।
robots.txt 告诉爬虫网站所有者不希望抓取哪些页面;即使它在法律上没有约束力,也应尊重。抓取个人数据、受版权保护的内容或违反网站服务条款,可能带来法律后果,且各国规定不同。不要让服务器过载,如实标明你的爬虫身份,有官方 API 或下载时优先使用。
Source 5 — Kaggle & Open Dataset Platforms 📚Source 5 — Kaggle और Open Dataset Platforms 📚来源 5 — Kaggle 与开放数据平台 📚
For learning, prototypes and competitions, curated platforms offer ready-to-use datasets. Always read each dataset's description and licence before use.
सीखने, prototypes और competitions के लिए curated platforms तैयार datasets देते हैं। इस्तेमाल से पहले हर dataset का विवरण और licence ज़रूर पढ़ें।
用于学习、原型和竞赛时,精选平台提供现成的数据集。使用前务必阅读每个数据集的说明和许可。
| PlatformPlatform平台 | FocusFocus方向 | Notable featureख़ास बात特色 |
|---|---|---|
| Kaggle | General ML, competitionsGeneral ML, competitions通用机器学习、竞赛 | Hundreds of thousands of public datasets; free notebooks with a weekly GPU quotaलाखों के आसपास public datasets; हफ़्ते के GPU quota वाले free notebooks数十万个公开数据集;有每周 GPU 配额的免费笔记本 |
| UCI ML Repository | Classic academic datasetsClassic academic datasets经典学术数据集 | Benchmarks such as Iris, Adult (census income) and WineIris, Adult (census income) और Wine जैसे benchmarksIris、Adult(人口收入)、Wine 等基准 |
| Hugging Face Hub | Text, images, audioText, images, audio文本、图像、音频 | One line: load_dataset("imdb")एक line: load_dataset("imdb")一行代码:load_dataset("imdb") |
| Google Dataset Search | All domainsसभी क्षेत्र全领域 | A search engine for public datasetsPublic datasets का search engine公开数据集搜索引擎 |
| data.gov / data.gov.in | Government dataसरकारी data政府数据 | Official public-sector data (US / India)Official सरकारी data (US / India)官方公共部门数据(美国 / 印度) |
Who Is in Your Data? — Sampling Bias 🎯आपके Data में कौन है? — Sampling Bias 🎯你的数据里有谁?— 抽样偏差 🎯
The Story: The Biggest Poll That Got It Wrongकहानी: सबसे बड़ा poll जो ग़लत निकला故事:规模最大却预测失败的民调
In 1936 the American magazine The Literary Digest mailed about 10 million ballots before the US presidential election and got 2.38 million back. It predicted that Alf Landon would beat Franklin Roosevelt with 57% of the vote. Roosevelt won with 60.8%. George Gallup, using about 50,000 people chosen with care, predicted a Roosevelt win.
1936 में अमेरिकी पत्रिका The Literary Digest ने राष्ट्रपति चुनाव से पहले लगभग 1 करोड़ ballots भेजे और 23.8 लाख वापस मिले। उसने अनुमान लगाया कि Alf Landon 57% वोट से Franklin Roosevelt को हराएँगे। Roosevelt 60.8% से जीते। George Gallup ने सोच-समझकर चुने लगभग 50,000 लोगों से Roosevelt की जीत का सही अनुमान लगाया।
1936 年美国总统大选前,《文学文摘》杂志寄出约 1,000 万张选票,收回 238 万张。它预测兰登将以 57% 的得票率击败罗斯福。结果罗斯福以 60.8% 获胜。乔治·盖洛普用精心挑选的约 5 万人,正确预测了罗斯福获胜。
What went wrong? The Digest's list came largely from its readers and from car and telephone owners — groups richer than average during the Great Depression. And people who disliked Roosevelt were more likely to send the ballot back (non-response bias). Size did not fix bias.
ग़लती कहाँ हुई? Digest की सूची ज़्यादातर उसके पाठकों और car व telephone मालिकों से आई थी — जो महामंदी के दौर में औसत से ज़्यादा अमीर थे। और Roosevelt को नापसंद करने वालों के ballot लौटाने की संभावना ज़्यादा थी (non-response bias)। आकार ने bias को ठीक नहीं किया।
问题出在哪里?《文学文摘》的名单主要来自它的读者以及汽车和电话拥有者 —— 在大萧条时期,这些人比一般人富裕。而且不喜欢罗斯福的人更愿意寄回选票(无应答偏差)。样本再大也治不了偏差。
Bars show the predicted or actual share for Roosevelt. Dashed line = 50%.
Bars, Roosevelt का अनुमानित या असली हिस्सा दिखाते हैं। Dashed line = 50%।
条形表示罗斯福的预测或实际得票率。虚线 = 50%。
| BiasBias偏差 | What happensक्या होता है发生了什么 | Exampleउदाहरण例子 |
|---|---|---|
| Selection / coverage biasSelection / coverage bias选择 / 覆盖偏差 | Some groups cannot get into the sampleकुछ groups sample में आ ही नहीं सकते某些群体根本进不了样本 | An online survey misses people without internetOnline survey इंटरनेट के बिना वाले लोगों को छोड़ देता है网络问卷漏掉没有网络的人 |
| Non-response biasNon-response bias无应答偏差 | Those who reply differ from those who do notजवाब देने वाले, न देने वालों से अलग होते हैं回复的人与不回复的人不同 | Only angry customers fill in the feedback formसिर्फ़ नाराज़ ग्राहक feedback form भरते हैं只有不满的顾客才填写反馈表 |
| Convenience samplingConvenience sampling方便抽样 | You sample whoever is easy to reachजो आसानी से मिल जाए, उसी से sample谁好找就抽谁 | Asking only students on your own campusसिर्फ़ अपने campus के छात्रों से पूछना只问自己校园的学生 |
| Survivorship biasSurvivorship bias幸存者偏差 | Only the "survivors" are recordedसिर्फ़ "बचे हुए" दर्ज होते हैं只记录了“幸存者” | Studying only companies still in businessसिर्फ़ चल रही companies का अध्ययन只研究仍在经营的公司 |
| Time bias / driftTime bias / drift时间偏差 / 漂移 | Data from one period does not match todayएक दौर का data आज से मेल नहीं खाता某一时期的数据与现在不符 | Shopping data collected only during a festival saleसिर्फ़ त्योहार sale के दौरान जुटाया shopping data只在节日促销期间收集的购物数据 |
600 people: 35% live in the city (where 30% support a plan) and 65% in villages (where 60% do). True support is 0.495. Try each method once, then repeat it 200 times and look where the estimates land.
600 लोग: 35% शहर में (जहाँ 30% योजना के समर्थक) और 65% गाँवों में (जहाँ 60%)। असली समर्थन 0.495 है। हर तरीका एक बार आज़माएँ, फिर 200 बार दोहराएँ और देखें कि अनुमान कहाँ गिरते हैं।
600 人:35% 住在城市(其中 30% 支持某计划),65% 住在乡村(其中 60% 支持)。真实支持率为 0.495。每种方法先试一次,再重复 200 次,看看估计值落在哪里。
Structured vs Semi-Structured vs Unstructured 🧩Structured बनाम Semi-Structured बनाम Unstructured 🧩结构化 vs 半结构化 vs 非结构化 🧩
Data also differs in shape. Structured data fits a table. Unstructured data — images, audio, free text — has no fixed fields. Semi-structured data sits in between: it has labels (keys or tags) but no fixed table layout.
Data अपने आकार में भी अलग होता है। Structured data table में बैठता है। Unstructured data — images, audio, खुला text — के कोई तय fields नहीं होते। Semi-structured data बीच में है: इसमें labels (keys या tags) होते हैं पर तय table layout नहीं।
数据的形态也各不相同。结构化数据能装进表格。非结构化数据 —— 图像、音频、自由文本 —— 没有固定字段。半结构化数据介于两者之间:有标签(键或标记),但没有固定的表格布局。
- Rows and columns, fixed schemaRows और columns, तय schema行与列,固定模式
- Stored in relational databases or CSVRelational databases या CSV में存于关系型数据库或 CSV
- Queried directly with SQLSQL से सीधे query可直接用 SQL 查询
- Easy with pandasPandas में आसान用 pandas 处理很方便
- Keys or tags label each fieldKeys या tags हर field का नाम बताते हैं键或标签标明字段
- No rigid schema; nesting allowedसख़्त schema नहीं; nesting की छूट无刚性模式,可嵌套
- Examples: JSON, XML, logs, emailsउदाहरण: JSON, XML, logs, emails例:JSON、XML、日志、邮件
- Parse and flatten before analysisAnalysis से पहले parse और flatten करें分析前需解析并展开
- No predefined fieldsकोई तय fields नहीं没有预定义字段
- Stored as files / in data lakes (S3, HDFS)Files / data lakes (S3, HDFS) में以文件形式存于数据湖(S3、HDFS)
- Usually needs NLP, computer vision or speech toolsआम तौर पर NLP, computer vision या speech tools चाहिए通常需要 NLP、计算机视觉或语音工具
- Examples: images, audio, video, free textउदाहरण: images, audio, video, खुला text例:图像、音频、视频、自由文本
You will often read that about 80% (sometimes 80–90%) of the world's data is unstructured. This is a widely repeated industry estimate, not a precise measurement, and it depends on whether you count bytes (videos are huge) or records. Treat it as "most data by volume is unstructured", not as an exact number.
आप अक्सर पढ़ेंगे कि दुनिया का लगभग 80% (कभी 80–90%) data unstructured है। यह बार-बार दोहराया गया industry अनुमान है, सटीक माप नहीं, और यह इस पर निर्भर है कि आप bytes गिनते हैं (videos बहुत बड़े होते हैं) या records। इसे "मात्रा में ज़्यादातर data unstructured है" समझें, सटीक संख्या नहीं।
你常会读到全球约 80%(有时说 80–90%)的数据是非结构化的。这是业界反复引用的估计,并非精确测量,而且取决于按字节数(视频体积巨大)还是按记录数来算。把它理解为“按体量计大部分数据是非结构化的”,而不是精确数字。
Structured Data — A Closer LookStructured Data — क़रीब से结构化数据 — 细看
| customer_id | name | age | purchase_amount | date |
|---|---|---|---|---|
| 1001 | Priya Sharma | 28 | 4500 | 2024-03-12 |
| 1002 | Arjun Mehta | 35 | 12200 | 2024-03-13 |
| 1003 | Deepa Nair | 42 | 8750 | 2024-03-14 |
Every row has the same fields and types, so you can run SELECT AVG(purchase_amount) FROM customers WHERE age > 30 at once. Notice that the amount is stored as a plain number (4500), not as text like "₹4,500" — currency symbols and commas belong in the display, not in the stored value.
हर row के fields और types एक जैसे हैं, इसलिए आप तुरंत SELECT AVG(purchase_amount) FROM customers WHERE age > 30 चला सकते हैं। ध्यान दें कि राशि एक सादी संख्या (4500) के रूप में रखी है, "₹4,500" जैसे text के रूप में नहीं — मुद्रा चिह्न और commas दिखाने के लिए हैं, रखी गई value के लिए नहीं।
每行字段和类型都相同,所以可以直接运行 SELECT AVG(purchase_amount) FROM customers WHERE age > 30。注意金额存为纯数字(4500),而不是“₹4,500”这样的文本 —— 货币符号和逗号属于显示格式,不该存进数据值。
Unstructured Data — A Closer LookUnstructured Data — क़रीब से非结构化数据 — 细看
| Data typeData प्रकार数据类型 | Exampleउदाहरण例子 | Techniqueतकनीक技术 | Python libraryPython libraryPython 库 |
|---|---|---|---|
| TextText文本 | Reviews, newsReviews, समाचार评论、新闻 | Tokenising, TF-IDF, embeddingsTokenising, TF-IDF, embeddings分词、TF-IDF、嵌入 | spaCy, NLTK, Transformers |
| ImageImage图像 | X-rays, product photosX-rays, product photosX 光片、商品图 | Convolutional neural networks, vision transformersConvolutional neural networks, vision transformers卷积神经网络、视觉 Transformer | OpenCV, Pillow, torchvision |
| AudioAudio音频 | Calls, music, speechCalls, music, speech通话、音乐、语音 | Spectrograms, speech-to-textSpectrograms, speech-to-text频谱图、语音转文字 | librosa, Whisper |
| VideoVideo视频 | CCTV, social mediaCCTV, social media监控、社交媒体 | Frame extraction + vision modelsFrame extraction + vision models抽帧 + 视觉模型 | OpenCV, ffmpeg |
| Scanned documentsScanned documents扫描文档 | Contracts, formsContracts, forms合同、表单 | OCR, layout parsingOCR, layout parsingOCR、版面解析 | pdfplumber, PyMuPDF, Tesseract |
Most ML algorithms need numbers in a table. So unstructured data is first turned into features: word counts, TF-IDF vectors or embeddings for text; pixel arrays or learned feature vectors for images. Once that is done, the data is structured.
ज़्यादातर ML algorithms को table में संख्याएँ चाहिए। इसलिए unstructured data को पहले features में बदला जाता है: text के लिए word counts, TF-IDF vectors या embeddings; images के लिए pixel arrays या सीखे गए feature vectors। इसके बाद data structured हो जाता है।
大多数机器学习算法需要表格形式的数字。所以要先把非结构化数据变成特征:文本用词频、TF-IDF 向量或嵌入;图像用像素数组或学到的特征向量。做完这一步,数据就变成结构化的了。
Ten real-world items appear one at a time. Put each into the right group. Read the explanation after each choice.
दस असली चीज़ें एक-एक करके आती हैं। हर एक को सही group में डालें। हर चुनाव के बाद व्याख्या पढ़ें।
十个真实例子逐个出现。把每个放进正确的组,每次选择后阅读解释。
Side by Side — The Three Shapes of Dataसाथ-साथ — Data के तीन आकार并排对比 — 数据的三种形态
| Propertyगुण属性 | StructuredStructured结构化 | Semi-structuredSemi-structured半结构化 | UnstructuredUnstructured非结构化 |
|---|---|---|---|
| SchemaSchema模式 | Fixedतय固定 | Flexibleलचीला灵活 | Noneनहीं无 |
| StorageStorage存储 | Relational DB, CSV, ParquetRelational DB, CSV, Parquet关系库、CSV、Parquet | Document stores, JSON/XML filesDocument stores, JSON/XML files文档库、JSON/XML 文件 | Object storage, data lakesObject storage, data lakes对象存储、数据湖 |
| SQL queriesSQL queriesSQL 查询 | Yesहाँ可以 | Partly (JSON functions)आंशिक (JSON functions)部分(JSON 函数) | Not directlyसीधे नहीं不能直接 |
| ML-readyML के लिए तैयार可直接建模 | Mostlyज़्यादातर基本可以 | After flatteningFlatten करने के बाद展开后 | After feature extractionFeature extraction के बाद提取特征后 |
| Share of data (rough estimate)Data का हिस्सा (मोटा अनुमान)数据占比(粗略估计) | a minorityकम हिस्सा少数 | a growing shareबढ़ता हिस्सा比例上升 | the majority by volumeमात्रा में ज़्यादातर按体量占多数 |
| Exampleउदाहरण例子 | Sales tableSales table销售表 | API JSON reply, logsAPI JSON जवाब, logsAPI JSON 响应、日志 | Reviews, images, callsReviews, images, calls评论、图像、通话 |
| Typical toolsआम tools常用工具 | SQL, pandas | json, lxml, MongoDB | spaCy, OpenCV, Transformers |
Python ImplementationPython ImplementationPython 实现
SQL to pandas, with safe parametersसुरक्षित parameters के साथ SQL से pandas用安全参数从 SQL 读入 pandas
# 1) Query a SQL database straight into pandas (an in-memory SQLite database)
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE sales (customer_id INTEGER, revenue REAL, year INTEGER);
INSERT INTO sales VALUES (1001, 4500, 2024), (1002, 12200, 2024),
(1003, 8750, 2024), (1004, 3100, 2023);
""")
query = "SELECT customer_id, revenue FROM sales WHERE year = ?"
df = pd.read_sql(query, conn, params=(2024,)) # use ? placeholders, never string-join user input
print(df)
print("average revenue 2024:", round(df.revenue.mean(), 2))
Parse JSON and back off on HTTP 429JSON parse करें और HTTP 429 पर backoff करें解析 JSON 并在 HTTP 429 时退避
# 2) Parse a JSON API response and retry politely on HTTP 429
import json, time, random
import pandas as pd
random.seed(0)
# A response body as an API might return it (nested JSON)
body = '''{"results": [
{"city": "Delhi", "weather": {"temp_c": 31.5, "humidity": 48}},
{"city": "Mumbai", "weather": {"temp_c": 29.0, "humidity": 77}},
{"city": "Shimla", "weather": {"temp_c": 14.2, "humidity": 60}}]}'''
data = json.loads(body)
print(pd.json_normalize(data["results"]))
# Exponential backoff with a fake server that is busy for the first 3 calls
def fake_get(attempt):
return 429 if attempt < 3 else 200
for attempt in range(6):
status = fake_get(attempt)
if status == 200:
print(f"attempt {attempt + 1}: 200 OK")
break
wait = 2 ** attempt + random.random() * 0.1 # 1, 2, 4, ... seconds plus a little jitter
print(f"attempt {attempt + 1}: {status} Too Many Requests -> wait {wait:.1f}s")
time.sleep(0) # in real code: time.sleep(wait)
Scrape a list into a tableएक list को scrape करके table बनाएँ把列表抓取成表格
# 3) Scrape a table from HTML with BeautifulSoup (HTML given as a string here)
from bs4 import BeautifulSoup
import pandas as pd
html = """
<ul class="books">
<li class="book"><h3>Data Basics</h3><span class="price">₹350</span><span class="stock">In stock</span></li>
<li class="book"><h3>Clean Code Notes</h3><span class="price">₹499</span><span class="stock">Sold out</span></li>
<li class="book"><h3>Charts for All</h3><span class="price">₹275</span><span class="stock">In stock</span></li>
</ul>"""
soup = BeautifulSoup(html, "html.parser")
rows = []
for li in soup.select("li.book"):
rows.append({
"title": li.select_one("h3").get_text(strip=True),
"price": int(li.select_one(".price").get_text().replace("₹", "")),
"in_stock": li.select_one(".stock").get_text() == "In stock",
})
print(pd.DataFrame(rows))
CSV vs Parquet: size and speed (your timings will differ)CSV बनाम Parquet: आकार और गति (आपकी timings अलग होंगी)CSV vs Parquet:大小与速度(你的计时会不同)
# 4) CSV vs Parquet: size on disk and time to read ONE column
import os, time
import numpy as np, pandas as pd
rng = np.random.default_rng(0)
n = 1_000_000
df = pd.DataFrame({
"user_id": np.arange(n),
"city": rng.choice(["Delhi", "Mumbai", "Pune", "Chennai"], n),
"amount": rng.gamma(2, 500, n).round(2),
"clicks": rng.poisson(3, n),
})
df.to_csv("sales.csv", index=False)
df.to_parquet("sales.parquet", index=False)
print(f"CSV size: {os.path.getsize('sales.csv') / 1e6:6.1f} MB")
print(f"Parquet size: {os.path.getsize('sales.parquet') / 1e6:6.1f} MB")
t = time.perf_counter(); a = pd.read_csv("sales.csv", usecols=["amount"]); t_csv = time.perf_counter() - t
t = time.perf_counter(); b = pd.read_parquet("sales.parquet", columns=["amount"]); t_pq = time.perf_counter() - t
print(f"read 'amount' from CSV: {t_csv:.3f} s")
print(f"read 'amount' from Parquet: {t_pq:.3f} s ({t_csv / t_pq:.0f}x faster here)")
os.remove("sales.csv"); os.remove("sales.parquet")
A huge biased sample vs a small random oneबड़ा biased sample बनाम छोटा random sample庞大的有偏样本 vs 小的随机样本
# 5) Sampling bias: a big biased sample loses to a small random one
import numpy as np
rng = np.random.default_rng(42)
N = 1_000_000
urban = rng.random(N) < 0.35 # 35% live in cities
support = np.where(urban, rng.random(N) < 0.30, # 30% support in cities
rng.random(N) < 0.60) # 60% support in villages
print(f"true support: {support.mean():.3f}")
idx = rng.choice(N, 1_000, replace=False) # simple random sample
print(f"random sample, n = 1,000: {support[idx].mean():.3f}")
city_only = np.flatnonzero(urban)
big = rng.choice(city_only, 100_000, replace=False) # huge, but cities only
print(f"city-only sample, n = 100,000: {support[big].mean():.3f}")
Golden Rules of Data CollectionData Collection के सुनहरे नियम数据收集的黄金法则
Data collection is not a one-time chore. It is an ongoing, careful process: choose sources deliberately, record what you did, check who is missing, protect people's data, and keep watching for drift as the world changes.
Data collection एक बार का काम नहीं है। यह लगातार चलने वाली, सावधान प्रक्रिया है: sources सोच-समझकर चुनें, जो किया उसे दर्ज करें, देखें कि कौन छूट गया, लोगों के data की रक्षा करें, और दुनिया बदलने पर drift पर नज़र रखें।
数据收集不是一次性的杂事,而是持续、细致的过程:审慎选择来源,记录所做的一切,检查谁被遗漏,保护个人数据,并随着世界变化持续关注数据漂移。