0Pricing
Pandas & NumPy Academy · درس

قواعد البثّ

افهم قواعد البثّ في NumPy لتتمكن من جمع مصفوفة أحادية الأبعاد مع كل صف في مصفوفة ثنائية الأبعاد من دون تكرار صريح.

قواعد البثّ درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

The Problem Broadcasting Solves

Broadcasting lets NumPy combine arrays of different but compatible shapes without copying data — the smaller one is stretched to fit the larger.

import numpy as np

# Adding a scalar to an array is the simplest broadcast
a = np.array([1, 2, 3])
print(a + 10)  # [11 12 13]
# Scalar 10 is 'broadcast' to shape (3,)

Broadcasting Rule 1: Prepend 1s

NumPy lines up shapes from the right. If one array has fewer dimensions, it pads the left with 1s — so a (3,) array acts like (1, 3) next to a (4, 3) one.

import numpy as np

m = np.ones((4, 3))
v = np.array([10, 20, 30])  # shape (3,) -> treated as (1, 3)

result = m + v   # shape (4, 3)
print(result)
# [[11. 21. 31.]
#  [11. 21. 31.]
#  [11. 21. 31.]
#  [11. 21. 31.]]

Broadcasting Rule 2: Stretch Size-1 Dimensions

Any dimension of size 1 can stretch to match the other array — no data is actually copied. Both arrays can stretch their size-1 dimensions at once.

import numpy as np

# (3, 1) + (1, 4)  -->  (3, 4)
col = np.array([[1], [2], [3]])    # shape (3, 1)
row = np.array([[10, 20, 30, 40]]) # shape (1, 4)
print((col + row).shape)  # (3, 4)
print(col + row)

Broadcasting Rule 3: Incompatible Shapes

If two dimensions aren't equal and neither is 1, broadcasting fails with a ValueError. Checking shapes first gives you a clear error, not a silent bug.

import numpy as np

a = np.ones(3)
b = np.ones(4)
try:
    a + b
except ValueError as e:
    print(e)
# operands could not be broadcast together with shapes (3,) (4,)

Practical: Subtracting the Column Mean

A classic move: subtract each column's mean from every row to centre your data. With keepdims=True, the mean keeps a shape that broadcasts cleanly.

import numpy as np

data = np.array([[1., 2., 3.],
                 [4., 5., 6.],
                 [7., 8., 9.]])

col_mean = data.mean(axis=0)          # shape (3,)
centred = data - col_mean             # broadcast along axis 0
print(centred)
# [[-3. -3. -3.]
#  [ 0.  0.  0.]
#  [ 3.  3.  3.]]

Practical: Row Normalisation

To make each row sum to 1, divide by its row sum. Use keepdims=True so the sum stays shape (n, 1) and broadcasts across the columns.

import numpy as np

m = np.array([[1., 2., 3.],
              [4., 5., 6.]])

row_sums = m.sum(axis=1, keepdims=True)  # shape (2, 1)
normed = m / row_sums
print(normed.round(3))
# [[0.167 0.333 0.5  ]
#  [0.267 0.333 0.4  ]]

Outer Products via Broadcasting

Reshape one array to (n, 1) and another to (1, m), then multiply — broadcasting builds the full outer product matrix for you, no loops needed.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30, 40])

outer = a[:, np.newaxis] * b[np.newaxis, :]
print(outer)
# [[ 10  20  30  40]
#  [ 20  40  60  80]
#  [ 30  60  90 120]]

Broadcasting with 3-D Arrays

Broadcasting scales to any dimensions. A batch of images shaped (100, 28, 28) can be centred by a per-pixel mean of (1, 28, 28) — NumPy stretches the 1.

import numpy as np

batch = np.random.rand(100, 28, 28)  # 100 images
pixel_mean = batch.mean(axis=0, keepdims=True)  # (1, 28, 28)
centred = batch - pixel_mean          # (100, 28, 28)
print(centred.shape)  # (100, 28, 28)

np.broadcast_to for Explicit Stretching

np.broadcast_to shows you exactly what a broadcast produces, as a read-only view with no copy. It's perfect for picturing how shapes line up.

import numpy as np

a = np.array([1, 2, 3])
view = np.broadcast_to(a, (4, 3))
print(view)
# [[1 2 3]
#  [1 2 3]
#  [1 2 3]
#  [1 2 3]]
print(view.flags.writeable)  # False

Visualising Compatible Shapes

A handy rule: line shapes up from the right and check each pair. They're compatible if they're equal or one is 1. Predict shapes before you run code!

# Shape compatibility examples:
# (3, 4) + (   4) -> (3, 4)  OK: 4==4, 1 implied
# (3, 4) + (3, 1) -> (3, 4)  OK: 4 vs 1, 3==3
# (2, 3, 4) + (3, 4) -> (2, 3, 4)  OK
# (3, 4) + (3,  ) -> ERROR: 4 vs 3
import numpy as np
print(np.zeros((3,4)).shape)       # (3, 4)
print((np.zeros((3,4)) + np.zeros(4)).shape)  # (3, 4)

Common Broadcasting Mistakes

The top broadcasting trap is forgetting keepdims=True after aggregating, so shapes misalign. When stuck, print(arr.shape) to see what's really going on.

import numpy as np

m = np.arange(6).reshape(2, 3)
row_max = m.max(axis=1)            # shape (2,)  NOT (2,1)
print(row_max.shape)               # (2,)
# m - row_max  -> ERROR: shapes (2,3) and (2,) misalign

row_max_col = row_max[:, np.newaxis]  # shape (2, 1)
print((m - row_max_col).shape)     # (2, 3)  OK

Quick Check

Test your understanding of NumPy broadcasting rules from this lesson.

Lesson Recap

You've got it! Broadcasting stretches size-1 dimensions, compares shapes from the right, and keepdims=True keeps axes so math lines up. Next: boolean masking.

الأسئلة الشائعة

هل درس «قواعد البثّ» مجاني؟

نعم — نص درس «قواعد البثّ» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

ماذا ستتعلم في «قواعد البثّ»؟

افهم قواعد البثّ في NumPy لتتمكن من جمع مصفوفة أحادية الأبعاد مع كل صف في مصفوفة ثنائية الأبعاد من دون تكرار صريح. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟

لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «قواعد البثّ»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟

نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الدوال الشاملة (ufuncs)
  2. دوال التجميع
  3. قواعد البثّ
  4. التنقية المنطقية والفهرسة المتقدمة
← العودة إلى Pandas & NumPy Academy