[CH01] 04. 판다스, 넘파이, 맷플롭립 이해하기

SoYeong Gwon·2022년 6월 29일
0

Introduction to NLP

목록 보기
1/3
post-thumbnail

본 게시물은 아래 wikidocs의 실습을 참고하여 작성되었습니다. https://wikidocs.net/book/2155

1. 판다스(Pandas)

  • Padas는 다음 세 가지의 데이터 구조를 사용함.
    • Series
    • DataFrame
    • Panel
import pandas as pd

(1) 시리즈(Series)

  • 시리즈 클래스는 1차원 배열의 값(values)와 각 값에 대응되는 인덱스(index)를 부여할 수 있는 구조를 가짐.
sr = pd.Series([17000,18000,1000,5000],
                index = ['피자','치킨','콜라','맥주'])
print('시리즈 출력 : ')
print('-' * 15)
print(sr)
시리즈 출력 : 
---------------
피자    17000
치킨    18000
콜라     1000
맥주     5000
dtype: int64
print('시리즈의 값 : {}'.format(sr.values))
print('시리즈의 인덱스 : {}'.format(sr.index))
시리즈의 값 : [17000 18000  1000  5000]
시리즈의 인덱스 : Index(['피자', '치킨', '콜라', '맥주'], dtype='object')

(2) 데이터프레임(DataFrame)

  • 2차원 리스트를 매개변수로 전달함.
  • 2차원이므로 행방향 인덱스(index)열방향 인덱스(column)가 존재함.
  • 데이터프레임은 열, 인덱스, 값으로 구성됨.
values = [[1,2,3],[4,5,6],[7,8,9]]
index = ['one','two','three']
columns = ['A','B','C']

df = pd.DataFrame(values, index=index, columns=columns)

print('데이터 프레임 출력:')
print('-'*18)
print(df)
데이터 프레임 출력:
------------------
       A  B  C
one    1  2  3
two    4  5  6
three  7  8  9
print('데이터프레임의 인덱스 : {}'.format(df.index))
print('데이터프레임의 열이름 : {}'.format(df.columns))
print('데이터프레임의 값 :')
print('-'*18)
print(df.values)
데이터프레임의 인덱스 : Index(['one', 'two', 'three'], dtype='object')
데이터프레임의 열이름 : Index(['A', 'B', 'C'], dtype='object')
데이터프레임의 값 :
------------------
[[1 2 3]
 [4 5 6]
 [7 8 9]]

(3) 데이터프레임의 생성

  • 리스트(List), 시리즈(Series), 딕셔너리(dict), Numpy로 부터 생성할 수 있음.
  • 리스트와 딕셔너리를 사용하여 데이터프레임을 생성

(1) 이중 리스트

data =[
    ['1000','Steve',90.72],
    ['1001','James',78.09],
    ['1002','Doyeon',98.43],
    ['1003','Jane',64.19],
    ['1004','Pilwoong',81.30],
    ['1005','Tony',99.14]
]

df=pd.DataFrame(data)
print(df)
      0         1      2
0  1000     Steve  90.72
1  1001     James  78.09
2  1002    Doyeon  98.43
3  1003      Jane  64.19
4  1004  Pilwoong  81.30
5  1005      Tony  99.14
# 생성된 데이터프레임에 열(columns)을 지정
df = pd.DataFrame(data,columns=['학번','이름','점수'])
print(df)
    학번        이름     점수
0  1000     Steve  90.72
1  1001     James  78.09
2  1002    Doyeon  98.43
3  1003      Jane  64.19
4  1004  Pilwoong  81.30
5  1005      Tony  99.14

(2) 딕셔너리

data = {
    '학번' : ['1000','1001','1002','1003','1004','1005'],
    '이름' : ['Steve','James','Doyeon','Jane','Pilwoong','Tony'],
    '점수' : [90.72,78.09,98.43,64.19,81.30,99.14]
}

df = pd.DataFrame(data)
print(df)
     학번        이름     점수
0  1000     Steve  90.72
1  1001     James  78.09
2  1002    Doyeon  98.43
3  1003      Jane  64.19
4  1004  Pilwoong  81.30
5  1005      Tony  99.14

(4) 데이터프레임 조회하기

아래의 명령어는 데이터프레임에서 원하는 구간만 확인하기 위한 것임.

  • df.head(n) - 앞 부분을 n개만 보기
  • df.tail(n) - 뒷 부분을 n개만 보기
  • df['열이름'] - 해당되는 열 확인
print(df.head(3))
     학번      이름     점수
0  1000   Steve  90.72
1  1001   James  78.09
2  1002  Doyeon  98.43
print(df.tail(3))
     학번        이름     점수
3  1003      Jane  64.19
4  1004  Pilwoong  81.30
5  1005      Tony  99.14
print(df['학번'])
0    1000
1    1001
2    1002
3    1003
4    1004
5    1005
Name: 학번, dtype: object

(5) 외부 데이터 읽기

  • pandas는 csv, 텍스트, excel, sql, html, json 등 다양한 데이터 파일을 읽고 데이터프레임을 생성할 수 있음.
df = pd.read_csv()

2. 넘파이(Numpy)

  • 수치 데이터를 다루는 파이썬 패키지
  • Numpy의 핵심이라고 불리는 다차원 행렬 자료구조인 ndarray를 통해 벡터 및 행렬을 사용하는 선형대수 계산에서 주로 사용됨.
  • Numpy는 편의성뿐만 아니라, 속도면에서도 압도적으로 빠름
import numpy as np

(1) np.array()

  • Numpy의 핵심은 ndarray
  • np.array()는 리스트, 튜플, 배열로부터 생성함
vec = np.array([1,2,3,4,5])
print(vec)
[1 2 3 4 5]
  • 2차원 배열을 만들때에는 array() 안에 하나의 리스트만 들어가므로 리스트의 리스트를 넣어야함.
mat = np.array([[10,20,30],[60,70,80]])
print(mat)
[[10 20 30]
 [60 70 80]]
print('vec의 타입 : ',type(vec))
print('mat의 타입 : ',type(mat))
vec의 타입 :  <class 'numpy.ndarray'>
mat의 타입 :  <class 'numpy.ndarray'>
  • ndim으로 축의 개수, shape로 크기를 볼 수 있음.
## vec 

print('vec의 축의 개수 : ', vec.ndim) # 축의 개수 출력
print('vec의 크기(shape) : ',vec.shape) # 크기 출력

##mat
print('mat의 축의 개수 :', mat.ndim) #축의 개수 출력
print('mat의 크기(shape) :', mat.shape) #크기 출력
vec의 축의 개수 :  1
vec의 크기(shape) :  (5,)
mat의 축의 개수 : 2
mat의 크기(shape) : (2, 3)

(2) ndarray의 초기화

  • ndarray를 만드는 다양한 방법이 있음.
  • np.zeros()는 배열의 모든 원소에 0을 삽입함.
# 모든 값이 0인 2x3 배열 생성
zero_mat = np.zeros((2,3)) 
print(zero_mat)
[[0. 0. 0.]
 [0. 0. 0.]]
  • np.ones()는 배열의 모든 원소에 1을 삽입함.
one_mat=np.ones((2,3))
print(one_mat)
[[1. 1. 1.]
 [1. 1. 1.]]
  • np.full()은 배열에 사용자가 지정한 값을 삽입함.
sames_value_mat = np.full((2,2),7)
print(sames_value_mat)
[[7 7]
 [7 7]]
  • np.eye()는 대각선으로 1이고 나머지는 0인 2차원 배열을 생성함.
eye_mat = np.eye(3)
print(eye_mat)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
  • np.random.random()은 임의의 값을 가지는 배열을 생성
random_mat = np.random.random((2,2))
print(random_mat)
[[0.80672845 0.30393819]
 [0.58899802 0.82808707]]

(3) np.arange()

  • np.arange(n)은 0부터 n-1까지의 값을 가지는 배열을 생성
range_vec = np.arange(10)
print(range_vec)
[0 1 2 3 4 5 6 7 8 9]
  • np.arange(i,j,k)는 i부터 j-1까지 k씩 증가하는 배열을 생성
n = 2
range_n_step_vec = np.arange(1,10,n)
print(range_n_step_vec)
[1 3 5 7 9]

(4) np.reshape()

  • np.reshape은 내부 데이터는 변경하지 않으면서 배열의 구조를 바꿈.
  • 0부터 29까지의 숫자를 생성하는 arange(30)을 구행한 후, 5행 6열의 행렬로 변경
reshape_mat = np.array(np.arange(30)).reshape((5,6))
print(reshape_mat)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]]

(5) Numpy 슬라이싱

  • 슬라이싱을 통해 특정 행이나 열의 원소에 접근할 수 있음.
mat = np.array([[1,2,3],[4,5,6]])
print(mat)
[[1 2 3]
 [4 5 6]]
slicing_mat = mat[0, :]
print(slicing_mat)
[1 2 3]
# 두번째 열 출력
slicing_mat = mat[:,1]
print(slicing_mat)
[2 5]

(6) Numpy 정수 인덱싱

  • 슬라이싱을 사용하면 배열의 부분배열을 추출할 수 있지만, 연속적이지 않은 원소로 배열을 만들 경우에는 슬라이싱으로 만들 수 없음.
  • 이런 경우 인덱싱을 사용하여 구성할 수 있음.
mat = np.array([[1,2],[4,5],[7,8]])
print(mat)
[[1 2]
 [4 5]
 [7 8]]
# 1행 0열의 원소
print(mat[1,0])
4
# 2행 1열, 0행 1열의 두개의 원소 추출 
indexing_mat = mat[[2,1],[0,1]]
print(indexing_mat)
[7 5]

(7) Numpy 연산

  • 사칙연산을 위한 내장함수가 있음.
    • np.add()
    • np.subtract()
    • np.multiply()
    • np.divide()
x = np.array([1,2,3])
y = np.array([4,5,6])
result1 = x + y
result2 = np.add(x,y)
print(result1, result2)
[5 7 9] [5 7 9]
result1 = x - y
result2 = np.subtract(x,y)
print(result1, result2)
[-3 -3 -3] [-3 -3 -3]
result1 = x * y
result2 = np.multiply(x,y)
print(result1, result2)
[ 4 10 18] [ 4 10 18]
result1 = x / y
result2 = np.divide(x,y)
print(result1, result2)
[0.25 0.4  0.5 ] [0.25 0.4  0.5 ]
  • Numpy에서 벡터와 행렬곱 또는 행렬곱을 위해서는 dot()을 사용해야함.
mat1 = np.array([[1,2],[3,4]])
mat2 = np.array([[5,6],[7,8]])
mat3 = np.dot(mat1,mat2)
print(mat3)
[[19 22]
 [43 50]]

3. 맷플롯립(Matplotlib)

  • 데이터를 차트, 플롯으로 시각화하는 패키지
import matplotlib.pyplot as plt

(1) 라인 플롯 그리기

  • plot()은 라인 플롯을 그리는 기능
  • x축, y축의 값을 기재하고 그림을 표시하는 show()를 통해 시각화
  • title()을 통해 제목 지정
plt.title('test')
plt.plot([1,2,3,4],[2,4,8,6])
plt.show()

(2) 축 레이블 삽입하기

  • plt.xlabel()
  • plt.ylabel()
plt.title('test')
plt.plot([1,2,3,4],[2,4,8,6])
plt.xlabel('hours')
plt.ylabel('score')
plt.show()

(3) 라인 추가와 범례 삼입하기

  • legend()를 사용하여 범례를 볼 수 있음.
plt.title('students')

plt.plot([1,2,3,4],[2,4,8,6])
plt.plot([1.5,2.5,3.5,4.5],[3,5,8,10])

plt.xlabel('hours')
plt.ylabel('score')

plt.legend(['A student','B student'])
plt.show()

0개의 댓글