[pandas] 2. Series

Series

인덱스
A 10
B 20
C 30
D 40
E 50
F 60

1. Series 생성방법 (3가지)

import pandas as pd
import numpy as np

## 첫번째 방법
series = pd.Series([10, 20, 30, 40, 50, 60],
                  index=['A','B','C','D','E','F'])

## 두번째 방법
series = pd.Series({
    'A':10,
    'B':20,
    'C':30,
    'D':40,
    'E':50,
    'F':60
})

## 세번째 방법
series = pd.Series(np.random.random(10))

print(series)
import pandas as pd
series = pd.Series([10, 20, 30],
                  index = ['A', 'B', 'C'])

print(series.index) # Index(['A', 'B', 'C'], dtype='object')
print(series.values) # [10 20 30]
print(type(series.values)) # numpy.ndArray

2. Series 연산

import pandas as pd
S_A = pd.Series([10, 20, 30], index = [1, 2, 3])
S_B = pd.Series([5, -3, 10], index = [3, 2, 1])

print(S_A + S_B) # {1: 20, 2: 17, 3: 35}
import pandas as pd
series = pd.Series([10, 20, 30], index = ['A', 'B', 'C'])

print(series + 1) # {A: 11, B: 21, C: 31}
print(series * 2) # {A: 20, B: 40, C: 60}
import pandas as pd
series = pd.Series(['17:30', '21:15', '22:00'])
series.str.split(':') # {0: [17, 30], 1: [21, 15], 2: [22, 00]}

series = pd.Series(['abc', 'def', 'hi'])
series.str.capitalize() # {0: Abc, 1: Def, 2: Hi}

3. 연산 실습

import pandas as pd
S_A = pd.Series([10, 20, 30], index = ['A', 'B', 'C'])
S_B = pd.Series([30, 20, 10, 50], index = ['A', 'B', 'C', 'D'])

print(S_A + S_B)
## A 40.0
## B 40.0
## C 40.0
## D NaN
## dtype: float64

print(S_A * S_B)
## A 300.0
## B 400.0
## C 300.0
## D NaN
## dtype: float64

본 실습에서는 Series에 문자열 함수를 적용해 보겠습니다.

아래의 코드를 실행하여 생성된 Series의 값인 smallvery small 에 대문자로 변환하는 문자열함수인 upper() 가 적용되는 것을 확인해 봅시다.

import pandas as pd
S_C = pd.Series(['small', 'very small'])

print(S_C.str.upper())
## 0 SMALL
## 1 VERY SMALL
## dtype: object