1. csv파일 읽어오기 - 특정 header 제거, 인덱스나 끝 부분 제거하기

data = []
file = open('distance_sample1.csv','r',encoding='utf-8')
reader = csv.reader(file)
for idx,line in enumerate(reader):
    # 0번째 컬럼을 스킵
    if idx != 0:
        # 0번째 row 스킵하고 1~4까지 저장 
        data.append(line[1:4])
    #print(idx,":",line)
file.close()

[['사과', '10', '9'],
 ['베이컨', '1', '4'],
 ['바나나', '10', '1'],
 ['당근', '7', '10'],
 ['샐러리', '3', '10'],
 ['치즈', '1', '1']]

 

## 특정 컬럼만 따로 리스트로 저장하기

import numpy as np
import csv
data2 = []
file = open('distance_sample1.csv','r',encoding='utf-8')
reader = csv.reader(file)
for idx,line in enumerate(reader):
    if idx != 0:
        data2.append(line[-1])
    #print(idx,":",line)
file.close()
data2
['과일', '단백질', '과일', '채소', '채소', '단백질']

 

2. 남자면 1, 여자면 2 로 데이터 성질을 변경

a = np.array(['남','여','남','여','여'])
res = np.where(a == '남',1,2)
print(res)

array([1, 2, 1, 2, 2])

 

3. 원핫인코딩 수행 - 컬럼1개를 n개로 

import numpy as np
a = np.array([0,1,2,2,2,1,0,0,1])
b = np.max(a) + 1
np.eye(b)[a]

array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.],
       [0., 1., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [0., 1., 0.]])
import numpy as np
a = np.array([1, 0, 3])
b = np.zeros((a.size, a.max()+1))
b[np.arange(a.size),a] = 1
print(b)
[[0. 1. 0. 0.]
 [1. 0. 0. 0.]
 [0. 0. 0. 1.]]

 

 

4. 파생된 파라미터를 원본과 결합

 

# data2 : 특정컬럼값 리스트를 0,1 로 변환한 리스트

f_list = np.array(data2)
res = np.where(f_list == '과일',0,1)
print(res)
[0 1 0 1 1 1]


b = np.max(res)+1
data3 = np.eye(b)[res]
[[1. 0.]
 [0. 1.]
 [1. 0.]
 [0. 1.]
 [0. 1.]
 [0. 1.]]

ndarray 로 변환하여 합쳐준다.

이때 np.eye() 값은 실수이므로 int 로 변환한다.

array1 = np.array(data)
array2 = np.array(data3, dtype='int')

array3 = np.concatenate([array1,array2],axis=1)
array3

array([['사과', '10', '9', '1', '0'],
       ['베이컨', '1', '4', '0', '1'],
       ['바나나', '10', '1', '1', '0'],
       ['당근', '7', '10', '0', '1'],
       ['샐러리', '3', '10', '0', '1'],
       ['치즈', '1', '1', '0', '1']], dtype='<U21')

 

 

5. 저장하기

# csv 로 저장해 보자 - savetxt
# np.loadtxt 로 읽어올 수 있다.

import numpy as np
import csv

np.savetxt('test.csv',array3,fmt="%s",delimiter=",")


array([['사과', '10', '9', '1', '0'],
       ['베이컨', '1', '4', '0', '1'],
       ['바나나', '10', '1', '1', '0'],
       ['당근', '7', '10', '0', '1'],
       ['샐러리', '3', '10', '0', '1'],
       ['치즈', '1', '1', '0', '1']], dtype='<U21')

 

 

 

'PYTHON' 카테고리의 다른 글

Pandas를 이용한 데이터 탐색 - 데이터 그룹분석  (0) 2021.07.01
Pandas  (0) 2021.07.01
Numpy 자주 사용하는 함수  (0) 2021.06.28
한글폰트 설정  (0) 2021.06.28
Numpy  (0) 2021.06.24

+ Recent posts