Numpy. section5 : ndarray의 원소별 연산과 브로드캐스팅. Lec17. ndarray의 원소별 연산

timekeeep·2023년 2월 25일

Numpy

목록 보기
16/28

[0] Element-wise Operations and Broadcasting

  • int, float와 bool == , != 연산시 typecast가 필요한 경우가 있다
  • 원소별 연산으로 for문없이 연산시 속도면에서 장점이 있다
# Element-wise Operations and Broadcasting

# Vector - Vector Case (원소별 연산이 이루어짐)

import numpy as np

a = np.random.randint(-5, 5, (5,))
b = np.random.randint(-5, 5, (5,))

print("a: ", a)
print("b: ", b, '\n')

print("a + b: ", a+b)
print("a - b: ", a-b)
print("a * b: ", a*b)
print("a / b: ", a/b)
print("a // b: ", a//b)
print("a % b: ", a%b)
print("a ** b: ", a**b)

print("a > b: ", a > b)
print("a >= b: ", a >= b)
print("a < b: ", a < b)
print("a <= b: ", a <= b)
print("a == b: ", a == b)
print("a != b: ", a != b)

# Matrix - Matrix Case

import numpy as np

M = np.random.randint(1, 5, (2,3))
N = np.random.randint(1, 5, (2,3))

print("M: \n", M)
print("N: \n", N ,'\n')

print("M + N: \n", M + N)
print("M - N: \n", M - N)

print("M > N: \n", M > N)
print("M >= N: \n", M >= N)

#Element-wise Multiplication and Masking

a = np.arange(5)
mask = np.array([0, 1, 0, 1, 0])

print("input: ", a)
print("mask: ", mask)
print("output: ", a*b)

a = np.arange(1,5).reshape((2,2))
mask = np.array([[0,0], [1,0]])

print("input: \n", a)
print("mask: \n", mask)
print("output: \n", a*mask)
profile
Those who are wise will shine like the brightness of the heavens, and those who lead many to righteousness, like the stars for ever and ever

0개의 댓글