0Pricing
Pandas & NumPy Academy · 강의

범용 함수(ufunc)

반복문을 작성하지 않고 np.sqrt, np.abs, np.exp, np.log와 같은 내장 원소별 함수를 배열에 적용합니다.

범용 함수(ufunc)은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Are ufuncs?

Universal functions (ufuncs) run a math operation on every element of an array at once, in fast compiled C — far quicker than a Python loop. ⚡

import numpy as np

a = np.array([1.0, 4.0, 9.0, 16.0])
print(np.sqrt(a))  # [1. 2. 3. 4.]
# Equivalent Python loop would be hundreds of times slower

Math ufuncs: sqrt, exp, log

All your favourite math functions are ufuncs: np.sqrt, np.exp, np.log, and more. They apply to whole arrays at once and handle edge cases gracefully.

import numpy as np

a = np.array([0.0, 1.0, 2.0, 3.0])
print(np.exp(a))         # [1.    2.718 7.389 20.086]
print(np.log(np.exp(a))) # [0. 1. 2. 3.]
print(np.log2(np.array([1, 2, 4, 8])))  # [0. 1. 2. 3.]

Trigonometric ufuncs

NumPy's trig ufuncs like np.sin and np.cos expect angles in radians. Use np.deg2rad to convert degrees first.

import numpy as np

angles = np.array([0, 30, 60, 90])
rad = np.deg2rad(angles)
print(np.sin(rad).round(4))  # [0.     0.5    0.866  1.   ]
print(np.cos(rad).round(4))  # [1.     0.866  0.5    0.   ]

np.abs, np.floor, np.ceil, np.round

For rounding, reach for np.floor (down), np.ceil (up), and np.round (nearest). They clean up float values across the whole array in one go.

import numpy as np

a = np.array([-2.7, 0.4, 1.5, 3.9])
print(np.abs(a))     # [2.7 0.4 1.5 3.9]
print(np.floor(a))   # [-3.  0.  1.  3.]
print(np.ceil(a))    # [-2.  1.  2.  4.]
print(np.round(a))   # [-3.  0.  2.  4.]

np.maximum and np.minimum

np.maximum(a, b) takes the larger value at each position from two arrays — different from np.max, which returns one number. np.maximum(a, 0) is ReLU!

import numpy as np

a = np.array([-3, 1, 5, -2, 4])
b = np.array([0, 0, 3, 3, 3])

print(np.maximum(a, b))  # [0 1 5 3 4]
print(np.minimum(a, b))  # [-3  0  3 -2  3]

# ReLU
print(np.maximum(a, 0))  # [0 1 5 0 4]

np.clip for Bounding Values

np.clip keeps every element inside a range: anything too low jumps up to the minimum, anything too high drops to the maximum. Great for bounding values.

import numpy as np

a = np.array([0.1, 0.5, -0.2, 1.3, 0.9])
clipped = np.clip(a, 0.0, 1.0)
print(clipped)  # [0.1 0.5 0.  1.  0.9]

ufuncs on Multi-Dimensional Arrays

ufuncs work on arrays of any shape. The math hits each element on its own, and the result keeps the same shape — no reshaping required.

import numpy as np

m = np.array([[1.0, 4.0], [9.0, 16.0]])
print(np.sqrt(m))
# [[1. 2.]
#  [3. 4.]]

out Parameter for Memory Efficiency

Every ufunc takes an out= argument to write results into an array you already have. That skips making a new array — handy in tight, memory-sensitive loops.

import numpy as np

a = np.array([1.0, 4.0, 9.0])
result = np.empty(3)
np.sqrt(a, out=result)  # write directly into result
print(result)  # [1. 2. 3.]

np.add.reduce and .accumulate

Each ufunc has a .reduce() method that combines all elements (np.add.reduce is just sum) and .accumulate() for running totals.

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.add.reduce(a))       # 15
print(np.add.accumulate(a))   # [ 1  3  6 10 15]
print(np.multiply.reduce(a))  # 120

np.frompyfunc for Custom ufuncs

np.frompyfunc turns any Python function into a ufunc you can apply to arrays. It's slower than built-ins, so save it for quick prototyping.

import numpy as np

def clamp_positive(x):
    return x if x > 0 else 0.0

vfunc = np.frompyfunc(clamp_positive, 1, 1)
a = np.array([-2, 3, -1, 5])
print(vfunc(a))  # [0.0 3 0.0 5]  (object dtype)

Comparing ufuncs to Python Loops

The speed gap is huge: on a million elements, a ufunc can be around 200 times faster than a Python loop. In number work, always reach for ufuncs first. 🚀

import numpy as np
import time

a = np.random.rand(1_000_000)

start = time.perf_counter()
np.sqrt(a)
print('ufunc:', round(time.perf_counter() - start, 4), 's')

start = time.perf_counter()
[x ** 0.5 for x in a]
print('loop:', round(time.perf_counter() - start, 4), 's')

Quick Check

Test your understanding of NumPy ufuncs from this lesson.

Lesson Recap

Nice work! ufuncs do element-wise math in fast C, cover sqrt, exp, log, and trig, and the out= argument saves memory. Next up: aggregation functions.

자주 묻는 질문

“범용 함수(ufunc)” 강의는 무료인가요?

네 — “범용 함수(ufunc)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“범용 함수(ufunc)”에서 뭘 배우나요?

반복문을 작성하지 않고 np.sqrt, np.abs, np.exp, np.log와 같은 내장 원소별 함수를 배열에 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“범용 함수(ufunc)” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 범용 함수(ufunc)
  2. 집계 함수
  3. 브로드캐스팅 규칙
  4. 불리언 마스킹과 고급 인덱싱
← Pandas & NumPy Academy(으)로 돌아가기