Pandas 기초 실습(Series)

Myeongsu Moon·2024년 10월 18일
0

제로베이스

목록 보기
10/95
post-thumbnail
import pandas as pd
import numpy as np
import random
from faker import Faker

random_seed = 42

Series

생성 & 구조

values = list(range(5))
index = [letter for letter in 'abcde']

print(values)
print(index)

결과
[0, 1, 2, 3, 4]      
['a', 'b', 'c', 'd', 'e']
series = pd.Series(values, index=index)
series

결과
a    0
b    1
c    2
d    3
e    4
dtype: int64
values[0] == series[0]

결과
True
py_dict = dict(zip(index,values))
py_dict

결과
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
series_dict = pd.Series(py_dict)
series_dict

결과
a    0
b    1
c    2
d    3
e    4
dtype: int64
list(py_dict.values()) == series_dict

결과
a    True
b    True
c    True
d    True
e    True
dtype: bool

인덱싱 & 슬라이싱

fake = Faker('ko_KR')
Faker.seed(random_seed)

names = [fake.name() for _ in range(10)]
ages = [random.randint(25,50) for _ in range(10)]
index = [chr(ord('A')+i) for i in range(10)]

print(names)
print(ages)
print(index)

결과
['김수민', '서정남', '김영자', '김영일', '김재호', '김은서', '김지원', '이민지', '이미숙', '홍예준']
[28, 45, 25, 25, 26, 38, 29, 43, 41, 48]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
ns = pd.Series(names,index=index)
ns

결과
A    김수민
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    이미숙
J    홍예준
dtype: object
print('ns[2]:',ns[2])
print("ns['D']:",ns['D'])

print("ns.loc['D']:",ns.loc['D'])
print("ns.iloc[2]:",ns.iloc[2])

print("ns.at['D']:",ns.at['D'])
print("ns.iat[2]:",ns.iat[2])

결과
ns[2]: 김영자
ns['D']: 김영일
ns.loc['D']: 김영일
ns.iloc[2]: 김영자
ns.at['D']: 김영일
ns.iat[2]: 김영자
tmp = pd.Series(names[:3],index=[0,2,5])
display(tmp)
print('tmp[0]:',tmp[0]) # 김수민
print('tmp.loc[2]:',tmp.loc[2]) # 서정남
print('tmp.iloc[2]:',tmp.iloc[2]) # 김영자
print('tmp[2]:',tmp[2])

결과
0    김수민
2    서정남
5    김영자
dtype: object

tmp[0]: 김수민
tmp.loc[2]: 서정남
tmp.iloc[2]: 김영자
tmp[2]: 서정남
display(ns)
new_ns = ns['B':'E']
display(new_ns)
print('ns:',ns.iloc[0])
print('new_ns:',new_ns.iloc[0])

결과
A    김수민
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    이미숙
J    홍예준
dtype: object

B    서정남
C    김영자
D    김영일
E    김재호
dtype: object

ns: 김수민
new_ns: 서정남

속성

ns

결과
A    김수민
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    이미숙
J    홍예준
dtype: object
ns.index

결과
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], dtype='object')
ns.values

결과
array(['김수민', '서정남', '김영자', '김영일', '김재호', '김은서', '김지원', '이민지', '이미숙', '홍예준'], dtype=object)
ns.hasnans
ns[0] = np.nan
print(ns)
print(ns.hasnans)

결과
A    NaN
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    이미숙
J    홍예준
dtype: object
True
ns.is_unique
ns['I':'J']='강상구'
display(ns)
ns.is_unique

결과
A    NaN
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    강상구
J    강상구
dtype: object

False
ns.name = '시리즈 테스트 - 이름'
ns

결과
A    NaN
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    강상구
J    강상구
Name: 시리즈 테스트 - 이름, dtype: object

기능

display(ns.head(15))
display(ns.tail(3))

결과
A    NaN
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    강상구
J    강상구
Name: 시리즈 테스트 - 이름, dtype: object

H    이민지
I    강상구
J    강상구
Name: 시리즈 테스트 - 이름, dtype: object
ns.unique()

결과
array([nan, '서정남', '김영자', '김영일', '김재호', '김은서', '김지원', '이민지', '강상구'], dtype=object)
ns.duplicated(keep='last')

결과
A    False
B    False
C    False
D    False
E    False
F    False
G    False
H    False
I     True
J    False
Name: 시리즈 테스트 - 이름, dtype: bool
ns.value_counts(normalize=True,dropna=False,sort=False)

결과
NaN    0.1
서정남    0.1
김영자    0.1
김영일    0.1
김재호    0.1
김은서    0.1
김지원    0.1
이민지    0.1
강상구    0.2
Name: 시리즈 테스트 - 이름, dtype: float64
# ns.sort_values(inplace=True)
display(ns)
sorted_ns = ns.sort_values(na_position='first')
display(sorted_ns)

결과
A    NaN
B    서정남
C    김영자
D    김영일
E    김재호
F    김은서
G    김지원
H    이민지
I    강상구
J    강상구
Name: 시리즈 테스트 - 이름, dtype: object

A    NaN
I    강상구
J    강상구
D    김영일
C    김영자
F    김은서
E    김재호
G    김지원
B    서정남
H    이민지
Name: 시리즈 테스트 - 이름, dtype: object
ns.describe()

결과
count       9
unique      8
top       강상구
freq        2
Name: 시리즈 테스트 - 이름, dtype: object
ages_sr = pd.Series(ages,index=index)
ages_sr

결과
A    45
B    40
C    44
D    44
E    31
F    32
G    31
H    40
I    41
J    45
dtype: int64
ages_sr.describe()

결과
count    10.000000
mean     39.300000
std       5.812821
min      31.000000
25%      34.000000
50%      40.500000
75%      44.000000
max      45.000000
dtype: float64
ages_sr.idxmax()
ages_sr['A'] = 50
ages_sr.idxmax()

결과
'A'
ns.add(' 님')

결과
A      NaN
B    서정남 님
C    김영자 님
D    김영일 님
E    김재호 님
F    김은서 님
G    김지원 님
H    이민지 님
I    강상구 님
J    강상구 님
Name: 시리즈 테스트 - 이름, dtype: object

이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다

0개의 댓글