본문 바로가기
study/python

파이썬 pandas - 시리즈(Series)

by kuah_ 2022. 7. 27.

 

 

 

Series

- 리스트와 유사하며 index 설정에 따라 딕셔너리처럼 사용할 수도 있는 자료구조

- 공식 문서 : https://pandas.pydata.org/docs/reference/api/pandas.Series.html 

 

pandas.Series — pandas 1.4.3 documentation

Values must be hashable and have the same length as data. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, …, n) if not provided. If data is dict-like and index is None, then the keys in the data are used as the index. If the ind

pandas.pydata.org

 

 

 

iterator를 Series로 변환

- 1.1 : 리스트(튜플도 가능)를 시리즈로 변환 (index=를 생략하면 자동으로 0부터 n까지로 지정됨)

- 1.2 : 딕셔너리를 시리즈로 변환

1
2
3
4
5
6
7
8
# 1.1
lotto1 = pd.Series([5111430333824], index=[1,2,3,4,5,6,'bonus'])
lotto1
 
# 1.2
ls = {1:52:113:144:305:336:38'bonus':24}
lotto2 = pd.Series(ls)
lotto2
cs

 

 

 

Q1. 아래와 같은 딕셔너리가 주어졌을 때, 시리즈를 생성하고 최대값과 최소값을 구하여 결과와 똑같이 출력.

1
2
3
4
5
6
7
jumsu = {
'글린다' : [50,60,50],
'엘파바' : [60,60,60],
'피예로' : [100,90,90],
'네사로즈' : [80,80,90],
'보크' : [95,95,95],
}
cs

결과

 

 

A. 

1
2
3
4
5
6
7
8
9
s_jumsu = pd.Series(jumsu) # import pandas as pd
for i in s_jumsu.index:
    print('-' + i + '-', end='-')
print()
for i in s_jumsu.values:
    print'-{:.2f}점-'.format( np.max(i)), end=''# import numpy as np
print()
for i in s_jumsu.values:
    print'-{:.2f}점-'.format( np.min(i)), end='')    
cs

 

 

 

Q2. 아래와 같은 딕셔너리가 주어졌을 때, 시리즈를 생성하고 학생별 평균값을 구하여 결과와 똑같이 출력.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
jumsu = {
'엘파바' : [50,60,50],
'글린다' : [60,60,60],
'피예로' : [100,90,90],
'네사로' : [80,80,90],
'보오크' : [50,45,50],
'비이크' : [80,70,66],
'마법사' : [64,49,50],
'모리블' : [60,50,50],
'딜라몬' : [50,45,51],
'갈린다' : [80,70,61],
'웨스턴' : [64,49,51],
'위치이' : [60,50,51],
'위키드' : [95,95,95]
}
cs

결과

 

 

A. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 2.1
s1_jumsu = pd.Series(jumsu)
s2_jumsu = pd.Series()
 
for index in s1_jumsu.index:
    avg = np.mean(s1_jumsu.get(index)) # np.mean은 numpy에서 제공하는 평균값 함수
    if avg < 60:
        s2_jumsu[index] = round(avg, 2)
 
for i in s2_jumsu.index:
    print(i, end='-')
print()
for i in s2_jumsu.values:
    print'{}-'.format(i), end='-')  
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 2.2
jumsu2 = dict({key : round(np.mean(value), 2for key, value in jumsu.items() if np.mean(value)<60})
''
딕셔너리 내부 코드는 아래 코드와 같음
for key, value in jumsu.items()
    if np.mean(value) < 60 :
        jumsu2[key] = round(np.mean(value), 2)
'''
jumsu3 = pd.Series(jumsu2)
for i in jumsu3.index:
    print(i, end="-")
print()
for i in jumsu3:
    print(i, end="--")
print()
cs

 

 

 

 

댓글