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

दिन 9: NumPy Maths, Broadcasting और Random

⏱ 2 hours📶 Beginner → Intermediate🎯 100% self-study
दिन 9 / 60

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

  • पूरे arrays पर vectorised गणित
  • Broadcasting: अलग shapes के बीच गणित
  • Aggregations: sum, mean, std, percentile, cumsum
  • np.where, clip, unique और sorting
  • Random numbers और Monte Carlo simulation

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

एक e-commerce company जानना चाहती है: “हर शहर में 10% और metro शहरों में 20% छूट दें तो 50,000 products की नई कीमतें क्या होंगी?” Broadcasting इसका जवाब एक line में देता है, और random simulation risk का अनुमान लगाता है।

Vectorised गणित

Python
import numpy as np
prices = np.array([499, 1299, 2499, 89, 15999])
qty = np.array([3, 1, 2, 10, 1])
print("Revenue per item:", prices * qty)
print("With 18% GST    :", (prices * 1.18).round(2))
print("Log prices      :", np.log10(prices).round(2))
print("Total revenue   :", (prices * qty).sum())
Revenue per item: [ 1497 1299 4998 890 15999] With 18% GST : [ 588.82 1532.82 2948.82 105.02 18878.82] Log prices : [2.7 3.11 3.4 1.95 4.2 ] Total revenue : 24683

Broadcasting

Broadcasting से NumPy छोटे array को खींचकर अलग shapes के arrays जोड़ता है – बिना copies, बिना loops। नियम: shapes दाएँ से मिलाएँ; sizes बराबर हों या 1।

A shapeB shapeResultचलेगा?
(5,)() scalar(5,)✅
(4, 3)(3,)(4, 3)✅ row repeated
(4, 3)(4, 1)(4, 3)✅ column repeated
(4, 3)(4,)—❌ 3 ≠ 4
Python
import numpy as np
# 3 cities × 4 products base prices
base = np.array([[100, 250, 400, 1200],
                 [110, 260, 420, 1250],
                 [ 95, 240, 390, 1180]])
city_discount = np.array([[0.20], [0.20], [0.10]])     # shape (3, 1): metro, metro, small city
product_gst = np.array([0.05, 0.12, 0.18, 0.18])       # shape (4,)
final = base * (1 - city_discount) * (1 + product_gst)
print(final.round(1))
[[ 84. 224. 377.6 1132.8] [ 92.4 233. 396.5 1180. ] [ 89.8 241.9 414.2 1253.2]]
Python
import numpy as np
scores = np.array([[78, 82, 69], [92, 88, 95], [65, 70, 58], [88, 79, 84]])
col_mean = scores.mean(axis=0)
print("Centred (score - subject mean):")
print((scores - col_mean).round(1))
z = (scores - scores.mean(axis=0)) / scores.std(axis=0)
print("Z-scores:")
print(z.round(2))
Centred (score - subject mean): [[ -2.8 2.2 -7.5] [ 11.2 8.2 18.5] [-15.8 -9.8 -18.5] [ 7.2 -0.8 7.5]] Z-scores: [[-0.26 0.35 -0.53] [ 1.08 1.27 1.31] [-1.51 -1.5 -1.31] [ 0.7 -0.12 0.53]]

Aggregations

Python
import numpy as np
daily_sales = np.array([42, 55, 38, 61, 70, 95, 88, 47, 52, 49, 66, 91, 99, 58])   # in thousands ₹
print("sum", daily_sales.sum(), "| mean", daily_sales.mean().round(2), "| median", np.median(daily_sales))
print("std", daily_sales.std().round(2), "| min", daily_sales.min(), "| max", daily_sales.max())
print("25th/75th percentile:", np.percentile(daily_sales, [25, 75]))
print("Running total:", daily_sales.cumsum()[:7])
print("Day-on-day change:", np.diff(daily_sales)[:6])
sum 911 | mean 65.07 | median 59.5 std 19.75 | min 38 | max 99 25th/75th percentile: [49.75 83.5 ] Running total: [ 42 97 135 196 266 361 449] Day-on-day change: [ 13 -17 23 9 25 -7]

np.where, clip, unique, sort

Python
import numpy as np
marks = np.array([35, 82, 47, 91, 28, 66, 73])
print(np.where(marks >= 40, "Pass", "Fail"))
print(np.select([marks >= 75, marks >= 40], ["Distinction", "Pass"], default="Fail"))
print(np.clip(marks + 15, 0, 100))                 # grace marks, max 100
cities = np.array(["Pune", "Delhi", "Pune", "Agra", "Delhi", "Pune"])
vals, counts = np.unique(cities, return_counts=True)
print({str(v): int(c) for v, c in zip(vals, counts)})
print(np.sort(marks)[::-1], np.argsort(marks)[::-1][:3])
['Fail' 'Pass' 'Pass' 'Pass' 'Fail' 'Pass' 'Pass'] ['Fail' 'Distinction' 'Pass' 'Distinction' 'Fail' 'Pass' 'Pass'] [ 50 97 62 100 43 81 88] {'Agra': 1, 'Delhi': 2, 'Pune': 3} [91 82 73 66 47 35 28] [3 1 6]

Random numbers

Python
import numpy as np
rng = np.random.default_rng(42)           # modern, reproducible generator
print(rng.integers(1, 7, size=10))        # 10 dice rolls
print(rng.random(3).round(3))             # 0–1 uniform
heights = rng.normal(loc=165, scale=8, size=1000)   # mean 165 cm, sd 8
print("mean", heights.mean().round(1), "| sd", heights.std().round(1))
print(rng.choice(["UPI", "Card", "Cash"], size=8, p=[0.6, 0.25, 0.15]))
[1 5 4 3 3 6 1 5 2 1] [0.976 0.761 0.786] mean 164.8 | sd 7.9 ['Card' 'UPI' 'UPI' 'UPI' 'Card' 'Cash' 'UPI' 'Card']
Python
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
heights = rng.normal(165, 8, 5000)
plt.hist(heights, bins=40, color="#0ea5e9", edgecolor="white")
plt.axvline(heights.mean(), color="red", linestyle="--", label=f"mean {heights.mean():.1f} cm")
plt.title("5,000 simulated student heights")
plt.xlabel("Height (cm)"); plt.ylabel("Students"); plt.legend()
plt.show()
Simulated heights का histogram जो bell curve बनाता है
rng.normal जानी-पहचानी bell curve बनाता है (Day 28 पर और)।

असली example: Monte Carlo risk simulation

एक छोटा café रोज़ 80 से 160 cups बेचता है (औसत 120)। हर cup ₹35 profit देता है और fixed cost (किराया, staff, बिजली) ₹4,100 रोज़ है। एक महीने में loss की संभावना क्या है? हम 10,000 महीने simulate करते हैं।

Python
import numpy as np
rng = np.random.default_rng(7)
months, days = 10_000, 30
cups = rng.normal(120, 22, size=(months, days)).clip(80, 160)    # broadcasting-friendly 2-D array
profit = (cups * 35 - 4100).sum(axis=1)                          # one value per month
print("Average monthly profit: ₹", round(profit.mean()))
print("Worst 5% month       : ₹", round(np.percentile(profit, 5)))
print("Chance of a loss     :", f"{(profit < 0).mean():.2%}")
print("Chance profit > ₹10,000:", f"{(profit > 10000).mean():.1%}")
Average monthly profit: ₹ 3008 Worst 5% month : ₹ -3555 Chance of a loss : 22.37% Chance profit > ₹10,000: 4.0%
💡 Simulate क्यों?

जब formulas कठिन हो जाएँ, हज़ारों random “what-if” दुनिया बनाकर भरोसेमंद जवाब मिलता है। Banks, insurers और supply-chain teams रोज़ Monte Carlo इस्तेमाल करती हैं।

🏅 आज के Job Skills

✔ Business calculations vectorise करना✔ Rows और columns पर broadcasting✔ Percentiles और cumsum से summary✔ Reproducible random simulations चलाना

Practice tasks

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

Task 1: Temperatures [30, 35, 41, 28] °C को एक line में °F (F = C × 9/5 + 32) में बदलें।
Solution देखें
Python
import numpy as np
c = np.array([30, 35, 41, 28])
print(c * 9 / 5 + 32)
[ 86. 95. 105.8 82.4]
Task 2: 3×3 array में 3 दुकानों (rows) की 3 महीनों की sales है। हर value को उस दुकान के total के % में दिखाएँ।
Solution देखें
Python
import numpy as np
s = np.array([[120, 150, 130], [80, 95, 125], [200, 180, 220]])
print((s / s.sum(axis=1, keepdims=True) * 100).round(1))
[[30. 37.5 32.5] [26.7 31.7 41.7] [33.3 30. 36.7]]
Task 3: दो dice के 100,000 rolls simulate करें और total 7 आने की probability का अनुमान लगाएँ।
Solution देखें
Python
import numpy as np
rng = np.random.default_rng(1)
rolls = rng.integers(1, 7, size=(100000, 2)).sum(axis=1)
print(round((rolls == 7).mean(), 4), "(exact = 1/6 = 0.1667)")
0.1662 (exact = 1/6 = 0.1667)

Quick quiz

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

1. Shapes (4, 3) और (3,) broadcast होकर…
(3,) row सभी 4 rows के लिए दोहराई जाती है।
2. np.where(a > 0, a, 0) क्या करता है?
जहाँ condition False है वहाँ तीसरा argument लगता है।
3. default_rng(42) क्यों?
Fixed seed random results को दोहराने योग्य बनाता है।
4. np.percentile(x, 50) बराबर…
50th percentile median है।
5. [2, 3, 5] का cumsum?
Running totals: 2, 2+3, 2+3+5।

Interview corner

💼 Interview Corner

Example के साथ broadcasting समझाइए।

(100, 3) matrix से column means का (3,) array घटाना: NumPy mean वाली row को बिना loops या extra memory के 100 बार दोहराकर element-wise घटाता है। Shapes दाएँ से मिलाए जाते हैं और बराबर या 1 होने चाहिए।

Monte Carlo simulation क्या है?

Random inputs के साथ process को कई बार चलाकर और नतीजों को summarise करके अनिश्चित मात्रा का अनुमान लगाना – जैसे मासिक loss की probability या project cost की range।

सारांश

  • Arrays पर गणित element-wise होता है – कोई loop नहीं।
  • Broadcasting (4,3) को (3,) या (4,1) से जोड़ता है।
  • sum, mean, std, percentile, cumsum तेज़ summary देते हैं।
  • default_rng(seed) reproducible simulations देता है।
➡️ आगे

Day 10: pandas – Series और DataFrames, वे tables जिन पर data scientist दिन भर काम करता है।

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

np.random.seed या default_rng?
नए code में rng = np.random.default_rng(seed) लिखें। पुराना np.random.seed अभी चलता है पर Generator API तेज़ और सुरक्षित है।
keepdims=True क्या है?
यह घटे हुए axis को size 1 के साथ रखता है, ताकि result original array के साथ broadcast हो – row totals के % के लिए काम का।
← Data Science (60 Days)
🔗

Share this topic with a friend

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

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

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

अगला topicदिन 10: Pandas Series और DataFrame आपकी प्रगति: 9 / 60 (15%) · Lesson 10 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

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

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

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

▶ CodingEasily on YouTube

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

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

▶ Channel subscribe करें