Numpy. section4 : ndarray 바꾸기. Lec16. ndarray의 dtype 바꾸기

timekeeep·2023년 2월 23일
0

Numpy

목록 보기
15/28

[1] ndarray.astype

  • data type을 바꾸어주는 api
  • -3을 bool에서 바꾸어줄때 true가 되는것. -3 == True 는 false임
  • .astype(bool)로 바꾸어준 다음에 비교해야함
import numpy as np

M = np.array([1,2,3], np.int8)
print(M.dtype)

N = M.astype(np.uint32)
O = M.astype(np.float32)

print(N.dtype)
print(O.dtype)


# uniform distribution 활용

M = np.random.uniform(low = -10, high = 10, size = (3,3))

print(M, '\n')
print(M.astype(np.int32))

'''[[-5.62445902  0.99728797  9.88674552]
 [ 7.10780999  7.32286628  8.76614678]
 [-3.75314433 -8.26783021  8.44921973]]

[[-5  0  9]
 [ 7  7  8]
 [-3 -8  8]]'''


# bool dtype ndarrays

bools = np.array([True, False])
print(f"bool: \n{bools}")

bools2ints = bools.astype(int) 
print(f"int: \n{bools2ints}")

bools2floats = bools.astype(float) 
print(f"float: \n{bools2floats}")

'''
bool:
[ True False]
int:
[1 0]
float:
[1. 0.]
'''

ints = np.array([-2, -1, 0, 1, 2])
floats = np.array([-2.5, -1.5, 0., 1.5, 2.5])

print(f"ints: \n{ints}")
print(f"floats: \n{floats}\n")

ints2bools = ints.astype(bool)
print(f"ints -> bools: \n{ints2bools}")

'''
ints:
[-2 -1  0  1  2]
floats:
[-2.5 -1.5  0.   1.5  2.5]

ints -> bools:
[ True  True False  True  True]
'''

floats2bools = floats.astype(bool)
print(f"floats -> bools: \n{floats2bools}")

# 중요한 순간은 바꾸어줄때

print(-3 == True, -3 == False)
print(3.14 == True, 3.14 == False)

print(0. == True, 0. == False)
print(1. == True, 1. == False)
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개의 댓글