Array Arithmetic and Broadcasting
In NumPy, you can do math directly on arrays without using loops.
This is called element-wise operations — and it’s fast and clean.
Array Arithmetic
If two arrays are the same size, NumPy will apply operations element by element.
a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) print(a + b) # [11 22 33] print(a * b) # [10 40 90]
You can also subtract, divide, or raise to powers: a - b
, a / b
, a ** 2
Broadcasting
If arrays are not the same shape, NumPy tries to match them using broadcasting.
This means smaller arrays are “stretched” so the operation can still work.
a = np.array([1, 2, 3]) b = 10 print(a + b) # [11 12 13]
NumPy applied + 10
to every element in a
.
It can also work between 2D and 1D arrays in some cases (you’ll see this in practice).
Summary
- Use
+
,-
,*
,/
,**
directly on arrays - Operations happen element-by-element
- Broadcasting allows arrays of different shapes to work together
What’s Next
You’ll now practice array arithmetic and see how broadcasting works in action.
What is the purpose of broadcasting in NumPy?
To perform operations only on arrays of the same shape.
To convert arrays into a different data type.
To allow operations between arrays of different shapes by stretching smaller arrays.
To perform operations on single elements of an array.
학습 자료
AI 튜터
디자인
업로드
수업 노트
즐겨찾기
도움말