판다스 데이터프레임과 시리즈
목차
판다스 데이터프레임과 시리즈
장점
: 방대한 양의 데이터 저장 가능
행, 열 단위로 데이터 조작가능
나만의 데이터 만들기
시리즈 만들기
S= pd.Series([‘한 열에 들어갈것들’,index=[‘인덱스 이름’]]
import pandas as pd
s = pd.Series(['Wes McKinney', 'Creator of Pandas'], index=['Person', 'Who'])
print(s)
Person Wes McKinney
Who Creator of Pandas
dtype: object
데이터 프레임 만들기
• 기본 구조
scientists = pd.DataFrame(
data={'Occupation': ['Chemist', 'Statistician'],
'Born': ['1920-07-25', '1876-06-13'],
'Died': ['1958-04-16', '1937-10-16'],
'Age': [37, 61]},
index=['Rosaline Franklin', 'William Gosset'],
columns=['Occupation', 'Born', 'Age', 'Died'])
print(scientists)
#columns=[] -> 데이터프레임의 열 순서
• 열 순서 고정
from collections import OrderedDict
scientists = pd.DataFrame(OrderedDict([
('Name', ['Rosaline Franklin', 'William Gosset']),
('Occupation', ['Chemist', 'Statistician']),
('Born', ['1920-07-25', '1876-06-13']),
('Died', ['1958-04-16', '1937-10-16']),
('Age', [37, 61])]))
print(scientists)

시리즈 다루기
데이터 프레임에서 시리즈 선택
• (위의 데이터에서 시리즈 추출) first_row = scientists.loc[‘William Gosset’]
타입-> 시리즈
출력-> 오브젝트(문자열로 인식)
• index, values 속성과 keys 메서드 사용
> print(first_row.index)
Index(['Occupation', 'Born', 'Died', 'Age'], dtype='object')
> print(first_row.values)]
['Statistician' '1876-06-13' '1937-10-16' 61]
> print(first_row.keys())
Index(['Occupation', 'Born', 'Died', 'Age'], dtype='object')
> print(first_row.index[0])
Occupation
> print(first_row.keys()[0])
Occupation
• 시리즈 메서드
시리즈와 불린 추출
• 나이가 많은 사람데이터만 추출
scientists = pd.read_csv('../data/scientists.csv')
ages = scientists['Age']
print(ages[ages > ages.mean()])
1 61
2 90
3 66
7 77
Name: Age, dtype: int64
• 불린 데이터 추출
print(ages > ages.mean())
0 False
1 True
2 True
3 True
4 False
5 False
6 False
7 True
Name: Age, dtype: bool
• 불린 데이터 True값 추출
manual_bool_values = [True, True, False, False, True, True, False, True]
print(ages[manual_bool_values])
0 37
1 61
4 56
5 45
7 77
Name: Age, dtype: int64
시리즈와 브로드캐스팅
• 백터: 시리즈처럼 여러 개의 값을 갖음
스칼라: 단순크기를 나타냄 • 백터 연산(같은 길이)
• 백터에 스칼라 연산
• 백터 연산(다른 길이)
누락값(NaN)처리
• sort_index 처리
ascending = True ->오름차순 정리
ascending = False ->내림차순 정리
• ascending = False 와 ascending = True 연산
ages+ ages 와 같음(index값으로 계산하기 떄문)
데이터프레임 다루기
불린 추출과 브로드 캐스팅
• 불린 추출하기
• bool 백터
• 브로드캐스팅(*2) 정수는 2배//문자열 2번 써짐
시리즈와 데이터프레임의 데이터 처리 • 날짜(문자열) 시간관련작업 유용 형태로
A = pd.to_datetime(scientists['Born'],format='%Y-%m-%d')
print(A)
0 1920-07-25
1 1876-06-13
2 1820-05-12
3 1867-11-07
4 1907-05-27
5 1813-03-15
6 1912-06-23
7 1777-04-30
Name: Born, dtype: datetime64[ns] -> ‘Died’도 똑같이 해줌
• 새로운 열 추가 데이터프레임 이름[‘추가 열 이름’], 데이터프레임 이름[‘추가 열 이름’]= (추가 행 이름, 추가 행 이름)
scientists['born_dt'], scientists['died_dt'] = (born_datetime, died_datetime)
print(scientists.head())
Name Born Died Age Occupation born_dt \
0 Rosaline Franklin 1920-07-25 1958-04-16 37 Chemist 1920-07-25
1 William Gosset 1876-06-13 1937-10-16 61 Statistician 1876-06-13
2 Florence Nightingale 1820-05-12 1910-08-13 90 Nurse 1820-05-12
3 Marie Curie 1867-11-07 1934-07-04 66 Chemist 1867-11-07
4 Rachel Carson 1907-05-27 1964-04-14 56 Biologist 1907-05-27
died_dt
0 1958-04-16
1 1937-10-16
2 1910-08-13
3 1934-07-04
4 1964-04-14
• 계산 열 추가(산 시간)
• 데이터 섞기 Import random // random.shuffle()
import random
random.seed(42)
random.shuffle(scientists['Age'])
print(scientists['Age'])
• 데이터프레임 열 삭제 문자열이름.drop([‘열 이름’], axis = 1)
scientists_dropped = scientists.drop(['Age'], axis=1)
print(scientists_dropped.columns)
Index(['Name', 'Born', 'Died', 'Occupation', 'born_dt', 'died_dt','age_days_dt'],dtype='object')
데이터 저장하고 불러오기
피클로 저장하기
:바이너리 형태(2진법)의 오브젝트로 저장
-> pd.read_pickle 매서드로 읽어야함
• 직렬화(시리즈)한 오브젝트 저장 :스프레드시트보다 더 작은 용량으로 데이터 저장
• 데이터프레임 저장
CSV파일과 TSV파일로 저장하기
• CSV파일
:데이터를 쉼표로 구분하여 저장 • TSV파일
:데이터를 탭으로 구분하여 저장 • to_csv 매서드로 데이터프레임을 CSV파일로 저장
scientists.to_csv(‘../output/scientists_df.csv’)
• to_csv 매서드로 데이터프레임을 TSV파일로 저장
scientists.to_csv(‘../output/scientists_df.tsv’, sep=’\t’)
+엑셀 저장
시리즈: X -> 데이터프레임으로 변경
데이터프레임: 엑셀파일로 바로 저장 가능 (xlwt 라이브러리 필요)