관리 메뉴

Leo's Garage

[Numpy] Data Split 본문

Study/파이썬

[Numpy] Data Split

LeoBehindK 2024. 9. 15. 10:39
728x90
반응형

Numpy에서 Matrix 형태로 Data를 선언한 뒤에 목적에 맞게 Column이나 Row로 분리할 수 있다. 

import numpy as np

data = np.array([[1,2,3],[4,5,6],[7,8,9]])

print('data is', data)

x = data[:,0] # convert data column 0 to row
print('x is', x)

y = data[:,1] # convert data column 1 to row
print('y is', y)

z = data[:,2] # convert data column 2 to row
print('z is', z)

a = data[0,:] # convert data row 0 to row
print('a is', a)

print('the shape of the x is ', x.shape)

x = np.expand_dims(x, axis = 1)

print('x is', x)

print('the shape of the x is ', x.shape)

t = data[:,-1]
print('t is', t)
print('the shape of the t is ', t.shape)

u = data[:,:-1]
print('u is', u)
print('the shape of the u is ', u.shape)

결과는 아래와 같이 나온다.

(base)  kimdawoon@gimdaun-ui-MacBook-Pro  ~/test_python   main  python python.py        
data is [[1 2 3]
 [4 5 6]
 [7 8 9]]
x is [1 4 7]
y is [2 5 8]
z is [3 6 9]
a is [1 2 3]
the shape of the x is  (3,)
x is [[1]
 [4]
 [7]]
the shape of the x is  (3, 1)
t is [3 6 9]
the shape of the t is  (3,)
u is [[1 2]
 [4 5]
 [7 8]]
the shape of the u is  (3, 2)

Data를 분리하면 1-D Array가 되는데 위와 같이 차원을 확장해주면, 2-D Array가 된다.

2-D Array로 만들어서 다음 연산에 활용해야 하면 위와 같이 처리해주면 된다. 

여기서 

t = data[:,-1]
print('t is', t)
print('the shape of the t is ', t.shape)

u = data[:,:-1]
print('u is', u)
print('the shape of the u is ', u.shape)


==================================

t is [3 6 9]
the shape of the t is  (3,)
u is [[1 2]
 [4 5]
 [7 8]]
the shape of the u is  (3, 2)

[:-1] 은 처음부터 ~ 마지막 index 전까지를 의미하고

[-1] 은 마지막 index를 의미함을 기억하자. 

728x90
반응형
Comments