NumPy 배열의 강력함

효율적인 Python 코드 작성

Logan Thomas

Scientific Software Technical Trainer, Enthought

NumPy 배열 개요

  • Python 리스트의 대안
nums_list = list(range(5))
[0, 1, 2, 3, 4]
import numpy as np

nums_np = np.array(range(5))
array([0, 1, 2, 3, 4])
효율적인 Python 코드 작성
# NumPy 배열의 동질성
nums_np_ints = np.array([1, 2, 3])
array([1, 2, 3])
nums_np_ints.dtype
dtype('int64')
nums_np_floats = np.array([1, 2.5, 3])
array([1. , 2.5, 3. ])
nums_np_floats.dtype
dtype('float64')
효율적인 Python 코드 작성

NumPy 배열 브로드캐스팅

  • Python 리스트는 브로드캐스팅을 지원하지 않음
nums = [-2, -1, 0, 1, 2]
nums ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
효율적인 Python 코드 작성
  • 리스트 방식
# for 루프 (비효율적)
sqrd_nums = []
for num in nums:
    sqrd_nums.append(num ** 2)
print(sqrd_nums)
[4, 1, 0, 1, 4]
# 리스트 컴프리헨션 (더 낫지만 최선은 아님)
sqrd_nums  = [num ** 2 for num in nums]

print(sqrd_nums)
[4, 1, 0, 1, 4]
효율적인 Python 코드 작성

NumPy 배열 브로드캐스팅

  • NumPy 배열 브로드캐스팅으로 해결
nums_np = np.array([-2, -1, 0, 1, 2])
nums_np ** 2
array([4, 1, 0, 1, 4])
효율적인 Python 코드 작성

기본 1차원 인덱싱 (리스트)

nums = [-2, -1, 0, 1, 2]
nums[2]
0
nums[-1]
2
nums[1:4]
[-1, 0, 1]

기본 1차원 인덱싱 (배열)

nums_np = np.array(nums)
nums_np[2]
0
nums_np[-1]
2
nums_np[1:4]
array([-1, 0, 1])
효율적인 Python 코드 작성
# 2-D list
nums2 = [ [1, 2, 3],
          [4, 5, 6] ]

  • 기본 2차원 인덱싱 (리스트)
nums2[0][1]
2
[row[0] for row in nums2]
[1, 4]
# 2-D array

nums2_np = np.array(nums2)

  • 기본 2차원 인덱싱 (배열)
nums2_np[0,1]
2
nums2_np[:,0]
array([1, 4])
효율적인 Python 코드 작성

NumPy 배열 불리언 인덱싱

nums = [-2, -1, 0, 1, 2]
nums_np =  np.array(nums)
  • 불리언 인덱싱
nums_np > 0
array([False, False, False,  True,  True])
nums_np[nums_np > 0]
array([1, 2])
효율적인 Python 코드 작성
  • 리스트에는 불리언 인덱싱이 없음
# for 루프 (비효율적)
pos = []
for num in nums:
    if num > 0:
        pos.append(num)
print(pos)
[1, 2]
# 리스트 컴프리헨션 (더 낫지만 최선은 아님)
pos = [num for num in nums if num > 0]
print(pos)
[1, 2]
효율적인 Python 코드 작성

강력한 NumPy 배열로 연습해 봅시다!

효율적인 Python 코드 작성

Preparing Video For Download...