list > numpy.ndarray 생성 및 타입 설정
list_1 = [50,30,5,56,6,65,7,4,3,63,36,4,5,6,34,55]
arr = np.array(list_1)
print(arr, arr.dtype, '\n')
arr = np.array(list_1, dtype='f4')
print(arr, arr.dtype, '\n')
arr = np.array(['abc', 'defasgbg'], dtype='S3')
print(arr, arr.dtype, '\n')
arr = np.array(['a', 'ab', 'abc'], dtype=np.string_)
print(arr, arr.dtype, '\n')
arr = np.array(['a', 'ab', 'abc'], dtype=np.unicode_)
print(arr, arr.dtype, '\n')
"""
[50 30 5 56 6 65 7 4 3 63 36 4 5 6 34 55] int32
[50. 30. 5. 56. 6. 65. 7. 4. 3. 63. 36. 4. 5. 6. 34. 55.] float32
[b'abc' b'def'] |S3
[b'a' b'ab' b'abc'] |S3
['a' 'ab' 'abc'] <U3
"""
ndarray 생성 방법
list_2 = [0,1,2,3,4,5,6,7,8,9,]
np.array(list_2)
np.array(range(10))
np.array([[1,2,3], [4,5,6]])
np.arange(0, 20)
np.arange(0, 20, 2)
np.linspace(0, 10, 20)
arr, step = np.linspace(0, 10, 20, endpoint=False, retstep=True)
특수한 ndarray 생성 방법
a = np.eye(7)
b = np.eye(5, k=-2)
c = np.identity(3)
d = np.ones((7,7))
e = np.ones_like(arr1)
f = np.zeros(8)
g = np.zeros_like(arr1)
h = np.full((2,3), 5)
i = np.full_like(arr1, 5)
j = np.diag(arr1)
k = np.diag(arr3)
난수 생성 및 활용 방법
np.random.seed(2)
np.arange(25).reshape(5,5)
np.random.seed(123)
np.random.rand(20)
np.random.rand(3, 3)
np.random.randint(1, 50)
np.random.randint(1, 100, 15)
np.random.rand()
np.random.random_sample(10)
np.random.random(10)
np.random.ranf(10)
np.random.sample(10)
np.random.choice(range(4), 15, replace=True, p=[0.3, 0.2, 0.1, 0.4])
np.random.choice(6, 15)
np.random.shuffle(arr)
np.random.permutation(arr)
반복으로 ndarray 생성
arr = [0, 1, 2]
np.repeat(arr, 3)
np.repeat(range(3), 3)
arr = [[1,2], [3,4]]
np.repeat(arr, [1,5], axis=0)
"""
[[1 2]
[3 4]
[3 4]
[3 4]
[3 4]
[3 4]]
"""
ndarray 정보 확인
x = np.array([[1,2,3], [4,5,6], [7,8,9]], dtype='i2')
print(x, '\n')
print(f'배열 타입 확인 {type(x)}')
print(f'배열 차원 확인 {x.ndim}')
print(f'배열 원소 개수 확인 {x.size}')
print(f'배열 모양 확인 {x.shape}')
print(f'각 배열 요소의 바이트 수 {x.itemsize}')
print(f'배열의 메모리 크기 {x.nbytes} \n')
np.info(x)
ndarray 수정
x = np.array([[1,2,3], [4,5,6], [7,8,9]], dtype='i2')
x.reshape(1,9)
x.astype(np.float32)
x.resize((2,3))
x.flatten()
x.ravel()
ndarray 추가, 수정, 삭제, 복사
arr = np.array(range(1,4))
print(arr)
# np.append(array, new_value, [axis])
arr1 = np.append(arr, 4)
arr2 = np.append(arr, [4,5,6])
print(arr1)
print(arr2)
# np.insert(array, index, new_value. [axis])
arr3 = np.insert(arr, 0, 100)
arr4 = np.insert(arr, 0, [1,2,3])
print(arr3)
print(arr4)
# np.delete(array, index)
arr5 = np.delete(arr, 0)
print(arr5)
# np.copy(array)
arr1 = np.copy(arr)
x = np.arange(1,17).reshape(4,4)
y = x.copy()
# np.concatenate((array, array), axis)
cat = np.concatenate((x,y))
print(cat)
cat = np.concatenate((x,y), axis=1)
print(cat)
댓글