[Pandas] 01. 시리즈(Series)

image


판다스는 데이터프레임과 시리즈라는 자료형과 데이터 분석을 위한 다양한 기능을 제공하는 파이썬 라이브러리이다.

데이터프레임과 시리즈는 리스트나 딕셔너리와 비슷하지만 데이터를 다루는 데 더 특화되어있다. 많은 양의 데이터를 저장할 수 있을 뿐만 아니라 스프레드 시트 프로그램을 사용하는 것처럼 행과 열 단위로 원하는 데이터를 조작할 수 있는 다양한 속성과 메서드를 제공한다.

우선, 판다스의 자료형인 데이터프레임과 시리즈의 생성과 수정, 그리고 데이터에 접근하는 방법에 대해 알아보도록 하겠다.

사용한 code

판다스 라이브러리 불러오기

import pandas as pd


1. Series

Series는 1차원 배열 형태로, DataFrame에서 하나의 컬럼으로만 구성된 것이 Series라고 할 수 있다. 데이터와 각 데이터의 위치정보를 담는 인덱스로 구성되어 있다.

1-1. Series 만들기

판다스의 Series() 메서드에 List나 Dictionary를 전달하여 생성

List 이용

  • name으로 Series의 이름을 지정해줄 수 있다.
  • index를 따로 지정해주지 않으면 자동으로 0부터 입력된다.
    • index를 지정하는 경우, data의 길이와 같아야한다.
s1 = pd.Series(data=['커피', '주스', '밀크티'], name='drinks')
print(s1)
[Output]
0     커피
1     주스
2    밀크티
Name: drinks, dtype: object


s1 = pd.Series(data = ['커피', '주스', '밀크티'], index = ['coffee', 'juice', 'milktea'])
print(s1)
[Output]
coffee      커피
juice       주스
milktea    밀크티

Dictionary 이용

  • Dictionary의 key가 index가 된다.
s2 = pd.Series({'coffee':'커피', 'juice':'주스', 'milktea':'밀크티})
print(s2)
[Output]
coffee      커피
juice       주스
milktea    밀크티
dtype: object


1-2. index, value, keys

  • index 속성 : 인덱스
  • value 속성 : 데이터
  • keys 메서드 : 인덱스 (index와 같은 역할)
print(s1.index)
print(s1.values)
print(s1.keys())
[Output]
Index(['coffee', 'juice', 'milktea'], dtype='object')

['커피' '주스' '밀크티']

Index(['coffee', 'juice', 'milktea'], dtype='object')


# index 속성의 첫번재 값을 추출
s1.index[0]
[Output]
'coffee'


# keys를 이용하여 index 속성의 첫번재 값을 추출
s1.keys()[0]
[Output]
'coffee'


1-3. 원소 삭제 - drop(labels, inplace)

  • labels : 지우고자 하는 원소의 인덱스
    • 지정한 인덱스명 또는 행번호 (index 지정한 경우는 행번호 불가능)
    • 여러개를 한번에 삭제하는 경우 리스트 사용
  • inplace : 객체 원본 변형 여부(default=False)
# 뒤에서도 계속 사용할 시리즈 형태
s1 = pd.Series(data = ['커피', '주스', '밀크티']) # 행번호 사용
s2 = pd.Series(data = ['커피', '주스', '밀크티'], index = ['coffee', 'juice', 'milktea']) # 인덱스명 지정


s1.drop(0)  #원본데이터는 바뀌지 않는다
print(s1)
[Output]
0     커피
1     주스
2    밀크티
dtype: object


s2.drop(['coffee', 'milktea'], inplace = True) # True : 원본데이터 변경
print(s2)
[Output]
juice    주스
dtype: object


1-4. 원소 선택

인덱스명 또는 행번호를 사용하여 원소 선택이 가능하다. 원소 선택 방법에 따라 결과값의 타입이 달라지는 것을 주의하자!

Output : string

행번호 이용

print(s1[1])
print(type(s1[1]))
[Output]
주스
<class 'str'>


# 인덱스가 지정되어있어도 행번호 사용 가능
print(s2[1])
print(type(s2[1]))
[Output]
주스
<class 'str'>


인덱스명 이용

print(s2['juice'])
print(type(s2['juice']))
[Output]
주스
<class 'str'>

Output : Series

  • Series객체[start:stop] (stop은 포함x)
    • 인덱스명에서는 stop 포함
  • Series객체[[행번호 리스트]]

행번호 이용

print(s1[1:3])
print(type(s1[1:3]))
[Output]
juice       주스
milktea    밀크티

<class 'pandas.core.series.Series'>


print(s1[[0,2]])
print(type(s1[[0,2]]))
[Output]
coffee      커피
milktea    밀크티

<class 'pandas.core.series.Series'>


인덱스명 이용

s2['coffe':'juice']
[Output]
coffee    커피
juice     주스


원소 1개를 Series로 선택하고 싶은 경우

Series객체[start:start+1]

print(s1[1:2])
print(type(s1[1:2]))
[Output]
juice    주스

<class 'pandas.core.series.Series'>


Series객체[[행번호]]

print(s1[[0]])
print(type(s1[[0]]))
[Output]
coffee    커피

<class 'pandas.core.series.Series'>


1-5. 수정, 추가, 삭제

1-6. 연산

Series와 숫자 연산

시리즈 개별 원소에 각각 숫자를 연산한 결과를 시리즈로 반환

score1 = pd.Series({'국어':30, '영어':45, '수학':12})
print(score1)
print(score1 + 50)
[Output]
국어    30
영어    45
수학    12

국어    80
영어    95
수학    62

Series와 Series 연산

index를 찾아 정렬한 후 같은 index의 data(value)들을 연산

score1 = pd.Series({'국어':100, '영어':80, '수학':90})
score2 = pd.Series({'수학':80, '국어':90, '영어':80})
print(score1)
print(score2)
[Output]
국어    100
영어     80
수학     90

수학    80
국어    90
영어    80
print(score1 + score2)
[Output]
국어    190
수학    170
영어    160

연산 메소드를 활용한 Series와 Series 연산

위의 연산과 동일하지만 누락된 데이터를 fill_value로 대체할 수 있다.

Series객체.add(Series객체, fill_value)

score1 = pd.Series({'국어':np.nan, '영어':80, '수학':90})
score2 = pd.Series({'수학':80, '국어':90})
print(score1)
print(score2)
[Output]
국어     NaN
영어    80.0
수학    90.0

수학    80
국어    90


  • fill_value를 사용하지 않으면 Nan값이 하나라도 있으면 결과값은 Nan
score1.add(score2)
[Output]
국어      NaN
수학    170.0
영어      NaN
  • fill_value : Nan을 대체할 값
score1.add(score2, fill_value=0)
[Output]
국어     90.0
수학    170.0
영어     80.0


score1.add(score2, fill_value=50)
[Output]
국어    140.0
수학    170.0
영어    130.0


참고자료
  • Do it! 데이터 분석을 위한 판다스 입문