Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔢 Week 2 – NumPy और Pandas  ·  दिन 11

दिन 11: CSV, Excel, JSON पढ़ें और Explore करें

⏱ 90 min📶 Intermediate🎯 100% self-study
दिन 11 / 60

✅ आज आप सीखेंगे

  • घंटे बचाने वाले read_csv options
  • Excel sheets पढ़ना और लिखना
  • APIs का JSON पढ़ना (json_normalize)
  • किसी भी नए dataset की 5-मिनट checklist
  • साफ़ results को CSV / Excel में save करना

🏢 असली दुनिया में

Manager सुबह 10 बजे 40 MB की Excel file भेजता है और 11 बजे तक पूछता है “इसमें क्या है?”। दोहराने योग्य read-and-explore routine से आप भरोसे से जवाब देते हैं – rows, columns, types, missing values, ranges और पहली हैरानियाँ।

read_csv – सबसे ज़्यादा इस्तेमाल होने वाला function

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
print(sales.shape)
print(sales.head(3))
(2000, 13) order_id order_date city region category product quantity unit_price discount payment_mode customer_age customer_gender rating 0 BK100359 2024-01-01 Delhi North Fashion Jeans 2 1220 0.0 UPI 48.0 Male 5.0 1 BK100422 2024-01-01 Mumbai West Fashion Sneakers 1 2327 0.1 UPI 44.0 Female 4.0 2 BK100744 2024-01-01 Mumbai West Grocery Tea 1kg 5 525 0.0 UPI 18.0 Male 4.5
Optionक्या करता हैExample
usecolsRead only some columns (less memory)usecols=["city", "unit_price"]
nrowsRead the first n rows (quick peek)nrows=1000
parse_datesConvert date text to real datesparse_dates=["order_date"]
dtypeForce a type, e.g. keep IDs as textdtype={"pincode": str}
sepOther separatorssep=";" or sep="\t"
na_valuesExtra words that mean missingna_values=["NA", "-", "?"]
encodingFiles from Excel/Windowsencoding="latin-1"
Python
import pandas as pd
small = pd.read_csv("sales_data.csv", usecols=["order_date", "city", "category", "unit_price"],
                    parse_dates=["order_date"], nrows=5)
print(small)
print(small.dtypes)
order_date city category unit_price 0 2024-01-01 Delhi Fashion 1220 1 2024-01-01 Mumbai Fashion 2327 2 2024-01-01 Mumbai Grocery 525 3 2024-01-01 Mumbai Books & Stationery 154 4 2024-01-01 Bengaluru Fashion 515 order_date datetime64[ns] city object category object unit_price int64 dtype: object
Python
import pandas as pd
from io import StringIO
raw = """id;city;pincode;amount
1;Pune;411001;450
2;Agra;-;?
3;Delhi;110001;1299"""
df = pd.read_csv(StringIO(raw), sep=";", dtype={"pincode": str}, na_values=["-", "?"])
print(df)
print(df.dtypes)
id city pincode amount 0 1 Pune 411001 450.0 1 2 Agra NaN NaN 2 3 Delhi 110001 1299.0 id int64 city object pincode object amount float64 dtype: object
💡 ID codes को text रखें

Pincodes, phone numbers और 012345 जैसे IDs numbers के रूप में पढ़ने पर शुरू का zero खो देते हैं। dtype={"pincode": str} लिखें।

Excel files

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
with pd.ExcelWriter("report.xlsx") as xl:                      # needs: pip install openpyxl
    sales[sales["region"] == "North"].to_excel(xl, sheet_name="North", index=False)
    sales[sales["region"] == "South"].to_excel(xl, sheet_name="South", index=False)
sheets = pd.read_excel("report.xlsx", sheet_name=None)        # all sheets -> dict
for name, df in sheets.items():
    print(name, df.shape)
north = pd.read_excel("report.xlsx", sheet_name="North", usecols="A:D", nrows=3)
print(north)
North (508, 13) South (654, 13) order_id order_date city region 0 BK100359 2024-01-01 Delhi North 1 BK100281 2024-01-02 Jaipur North 2 BK100294 2024-01-02 Delhi North

JSON और APIs

Python
import pandas as pd
api_response = [
    {"id": 1, "customer": {"name": "Riya", "city": "Pune"}, "items": 3, "total": 1450},
    {"id": 2, "customer": {"name": "Om", "city": "Delhi"}, "items": 1, "total": 15999},
]
flat = pd.json_normalize(api_response)             # nested keys -> columns
print(flat)
flat.to_json("orders.json", orient="records", indent=2)
print(pd.read_json("orders.json").shape)
id items total customer.name customer.city 0 1 3 1450 Riya Pune 1 2 1 15999 Om Delhi (2, 5)
Python – reading straight from a URL (works the same way)
url = "https://example.com/data/sales.csv"     # any public CSV link
df = pd.read_csv(url)
# APIs:  import requests;  data = requests.get(api_url).json();  pd.json_normalize(data)

5-मिनट exploration checklist

  1. 1df.shape – कितना बड़ा?
  2. 2df.head() / df.sample(5) – row कैसी दिखती है?
  3. 3df.info() – column types और missing counts
  4. 4df.describe() – numbers की ranges; असंभव values पकड़ें
  5. 5df.isna().sum() और df.nunique() – gaps और categories
  6. 6df["col"].value_counts() – बड़ी categories
हर नए dataset पर ये चलाएँ
Python
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print("Shape:", df.shape)
print(df.sample(3, random_state=1))
df.info()
Shape: (3000, 13) customer_id gender senior_citizen tenure_months contract internet_service tech_support payment_method monthly_charges total_charges \ 1957 CUST11958 Female 1 41 Monthly NaN No internet UPI AutoPay 186.0 7475.0 2087 CUST12088 Male 0 33 Monthly Fiber No Bank Transfer 687.0 22982.0 1394 CUST11395 Female 0 60 Monthly NaN No internet Cash 277.0 16529.0 complaints data_usage_gb churn 1957 0 4.2 No 2087 2 61.6 No 1394 1 4.6 No <class 'pandas.core.frame.DataFrame'> RangeIndex: 3000 entries, 0 to 2999 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 customer_id 3000 non-null object 1 gender 3000 non-null object 2 senior_citizen 3000 non-null int64 3 tenure_months 3000 non-null int64 4 contract 3000 non-null object 5 internet_service 2375 non-null object 6 tech_support 3000 non-null object 7 payment_method 3000 non-null object 8 monthly_charges 3000 non-null float64 9 total_charges 2975 non-null float64 10 complaints 3000 non-null int64 11 data_usage_gb 3000 non-null float64 12 churn 3000 non-null object dtypes: float64(3), int64(3), object(7) memory usage: 304.8+ KB
Python
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print(df.describe().round(1))
print("\nMissing values:\n", df.isna().sum()[df.isna().sum() > 0])
print("\nUnique values per column:\n", df.nunique())
senior_citizen tenure_months monthly_charges total_charges complaints data_usage_gb count 3000.0 3000.0 3000.0 2975.0 3000.0 3000.0 mean 0.2 36.1 672.0 23946.4 0.9 57.8 std 0.4 20.6 263.2 17373.9 1.0 42.4 min 0.0 1.0 149.0 189.0 0.0 1.0 25% 0.0 18.0 459.0 9853.0 0.0 26.0 50% 0.0 35.0 679.0 20170.0 1.0 55.6 75% 0.0 54.0 881.0 35249.5 1.0 83.2 max 1.0 72.0 1408.0 84303.0 8.0 298.5 Missing values: internet_service 625 total_charges 25 dtype: int64 Unique values per column: customer_id 3000 gender 2 senior_citizen 2 tenure_months 72 contract 3 internet_service 2 tech_support 3 payment_method 4 monthly_charges 961 total_charges 2894 complaints 8 data_usage_gb 1112 churn 2 dtype: int64
Python
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print(df["contract"].value_counts())
print(df["churn"].value_counts(normalize=True).round(3))
print(df.describe(include="object"))
contract Monthly 1643 One year 757 Two year 600 Name: count, dtype: int64 churn No 0.709 Yes 0.291 Name: proportion, dtype: float64 customer_id gender contract internet_service tech_support payment_method churn count 3000 3000 3000 2375 3000 3000 3000 unique 3000 2 3 2 3 4 2 top CUST10001 Male Monthly Fiber No UPI AutoPay No freq 1 1520 1643 1327 1548 911 2126
🔎 पहली हैरानियाँ

5 मिनट में हम जान गए: 3,000 customers, 25 missing total_charges, 29% churn हुए, और ज़्यादातर customers monthly contract पर हैं। ऐसे notes लिखते रहें – यही आपके project की “Insights” slide बनेंगे (Day 57)।

Results save करना

Python
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
monthly = df[df["contract"] == "Monthly"]
monthly.to_csv("monthly_customers.csv", index=False)
print("Saved", len(monthly), "rows;", round(len(monthly) / len(df) * 100, 1), "% of customers")
print(pd.read_csv("monthly_customers.csv").columns.tolist()[:5])
Saved 1643 rows; 54.8 % of customers ['customer_id', 'gender', 'senior_citizen', 'tenure_months', 'contract']

🏅 आज के Job Skills

✔ सही options के साथ CSV पढ़ना✔ Multi-sheet Excel पढ़ना-लिखना✔ APIs का JSON flatten करना✔ Checklist से कोई भी dataset explore करना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: house_prices.csv से सिर्फ़ city, area_sqft और price_lakh पढ़ें और 3 सबसे बड़े घर print करें।
Solution देखें
Python
import pandas as pd
h = pd.read_csv("house_prices.csv", usecols=["city", "area_sqft", "price_lakh"])
print(h.nlargest(3, "area_sqft"))
city area_sqft price_lakh 290 Hyderabad 3080 199.97 742 Pune 2790 158.92 56 Bengaluru 2740 145.01
Task 2: loan_applications.csv पर 5-मिनट checklist चलाएँ। कितने % applications approve हुईं?
Solution देखें
Python
import pandas as pd
loans = pd.read_csv("loan_applications.csv")
print(loans.shape, loans.isna().sum().sum())
print(loans["approved"].mean().round(3))
(1200, 7) 0 0.462
Task 3: sales_data.csv के Electronics orders को Excel file में save करें, हर region की अलग sheet।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. कौन सा option सिर्फ़ पहली 100 rows पढ़ता है?
nrows पढ़ी जाने वाली rows सीमित करता है।
2. dtype={"pincode": str} क्यों?
Codes labels हैं, numbers नहीं।
3. pd.read_excel(file, sheet_name=None) क्या लौटाता है?
हर key sheet name, हर value DataFrame।
4. कौन सा function nested JSON को columns में बदलता है?
customer.name, customer.city columns बन जाते हैं।
5. to_csv(..., index=False) किससे बचाता है?
इसके बिना row numbers column के रूप में लिखे जाते हैं।

Interview corner

💼 Interview Corner

नए dataset के साथ सबसे पहले क्या करते हैं?

Size और कुछ sample rows देखते हैं, फिर types और missing values के लिए info(), ranges और असंभव values के लिए describe(), categories के लिए nunique()/value_counts(), और modelling से पहले सवाल व data-quality issues लिखते हैं।

Memory से बड़ी file pandas से कैसे पढ़ेंगे?

usecols और सही dtypes (category, int32) से छोटा करें, या chunksize से chunks में पढ़कर हर chunk aggregate करें; बहुत बड़े data के लिए database, Parquet files या Polars/Spark जैसे tools।

सारांश

  • usecols, nrows, parse_dates, dtype और na_values के साथ read_csv।
  • read_excel / to_excel multi-sheet workbooks संभालते हैं।
  • json_normalize API data को flatten करता है।
  • Checklist: shape → head → info → describe → isna/nunique → value_counts।
➡️ आगे

Day 12: loc, iloc, boolean filters, query और sorting से ठीक वही rows और columns चुनें जो चाहिए।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Excel file पर “Missing optional dependency openpyxl”?
एक बार pip install openpyxl चलाएँ। पुरानी .xls files के लिए pip install xlrd।
CSV पढ़ते समय UnicodeDecodeError?
File UTF-8 नहीं है। encoding="latin-1" या encoding="cp1252" आज़माएँ (Windows पर Excel exports में आम)।
Parquet क्या है?
Compressed, column-based file format जो CSV से बहुत छोटा और तेज़ है। Companies बड़े data के लिए इसे इस्तेमाल करती हैं: df.to_parquet() और pd.read_parquet()।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 12: Selecting, Filtering और Sorting आपकी प्रगति: 11 / 60 (18%) · Lesson 12 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें