🌒

2일차 Pandas

notion imagenotion image

목차

pandas

  • Python에서 사용하는 데이터를 분석하는 라이브러리
  • 행과 열을 쉽게 처리할 수 있는 함수를 제공하는 도구
  • numpy보다 유연하게 수치연산 가능
  • numpy는 데이터 누락을 허락하지 않지만, pandas는 데이터 누락을 허락
import pandas as pd import numpy as np # 버전 확인 print(pd.__version__) print(np.__version__) pd? # tab누르면 사용가능한 여러가지 method를 볼 수 있다. np?
Out[-] 1.0.1 1.18.1

Series

  • 인덱스와 values로 이루어진 1차원 배열
  • 모든 유형의 데이터를 보유할 수 있음
  • 인덱스를 지정해 줄 수 있음
  • 명시적 인덱스와 암묵적 인덱스를 가짐
 

Series 형태

  • RangeIndex : 인덱스 자동 생성
data = [100, 200, 300, 400, 500] pd.Series(data)
Out[-] 0 100 1 200 2 300 3 400 4 500 dtype: int64
print(pd.Series(data)[0]) print(pd.Series(data)[0:3]) print(pd.Series(data)[::-1]) # 역순
Out[-] 100 0 100 1 200 2 300 dtype: int64 4 500 3 400 2 300 1 200 0 100 dtype: int64
d = pd.Series(data) print(d.values) print(d.index)
Out[-] [100 200 300 400 500] RangeIndex(start=0, stop=5, step=1)
d = pd.Series(data, index=['a', 'b', 'c', 'd', 'e']) # 인덱스 지정 print(d) print(d.values) print(d.index)
 

Series 산술 연산

Out[-] a 100 b 200 c 300 d 400 e 500 dtype: int64 [100 200 300 400 500] Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print(d + 100) print(d * 2) print(d // 2) print(d ** 2)
Out[-] a 200 b 300 c 400 d 500 e 600 dtype: int64 a 200 b 400 c 600 d 800 e 1000 dtype: int64 a 50 b 100 c 150 d 200 e 250 dtype: int64 a 10000 b 40000 c 90000 d 160000 e 250000 dtype: int64
 

Series indexing , slicing

print(d['a']) print(d[::-1]) print(d[::2]) # 전체에서 두 칸씩 건너 뛰면서 출력 print(d.a) print(d.b) print(d.c)
Out[-] 100 e 500 d 400 c 300 b 200 a 100 dtype: int64 a 100 c 300 e 500 dtype: int64 100 200 300
d[d>300]
Out[-] d 400 e 500 dtype: int64
d > 300
Out[-] a False b False c False d True e True dtype: bool
for i in d: print(i)
Out[-] 100 200 300 400 500
# 딕셔너리 형태도 Series로 만들 수 있음 dic = { '2015년':1000000, '2016년':2000000, '2017년':3000000, '2018년':4000000, '2019년':11000000, '2020년':30000000, } pd.Series(dic)['2018년':]
Out[-] 2018년 4000000 2019년 11000000 2020년 30000000 dtype: int64
pd.Series(dic)[-3:] # 뒤에서 3번째까지 출력
Out[-] 2018년 4000000 2019년 11000000 2020년 30000000 dtype: int64
dic = { '2015년':1000000, '2016년':2000000, '2017년':3000000, '2018년':4000000, '2019년':11000000, '2020년':30000000, } pd.Series(dic, index=['2017년', '2019년', '2020년'])
Out[-] 2017년 3000000 2019년 11000000 2020년 30000000 dtype: int64
 

Series에 key, value, index

  • index
    • Series, DataFrame의 레코드를 식별
    • 집합 연산이 가능
  • loc : 인덱스를 기반으로 행 데이터를 읽음
  • iloc : 행 번호를 기반으로 행 데이터를 읽음
  • items() : key와 value를 튜플로 묶어서 리턴
  • 팬시 인덱싱 : 스칼라 대신 인덱스 배열을 리턴
s = pd.Series(dic) print('2015년' in s) print(1000000 in s)
Out[-] True False
print('2015년' in dic) print(1000000 in dic)
Out[-] True False
s.keys()
Out[-] Index(['2015년', '2016년', '2017년', '2018년', '2019년', '2020년'], dtype='object')
list(s.items()) # Series에서는 values를 허락하지 않음 # items를 통해서 values 확인
Out[-] [('2015년', 1000000), ('2016년', 2000000), ('2017년', 3000000), ('2018년', 4000000), ('2019년', 11000000), ('2020년', 30000000)]
# 딕셔너리에서는 key, value, item을 다 허락 print(dic.keys()) print(dic.values()) print(dic.items())
Out[-] dict_keys(['2015년', '2016년', '2017년', '2018년', '2019년', '2020년']) dict_values([1000000, 2000000, 3000000, 4000000, 11000000, 30000000]) dict_items([('2015년', 1000000), ('2016년', 2000000), ('2017년', 3000000), ('2018년', 4000000), ('2019년', 11000000), ('2020년', 30000000)])
s
Out[-] 2015년 1000000 2016년 2000000 2017년 3000000 2018년 4000000 2019년 11000000 2020년 30000000 dtype: int64
s[['2017년', '2020년']] # 팬시 인덱싱
Out[-] 2017년 3000000 2020년 30000000 dtype: int64
data = ['a', 'b', 'c', 'd', 'e'] pd.Series(data)[::2] # 두 칸씩 슬라이싱
Out[-] 0 a 2 c 4 e dtype: object
pd.Series(data, index=[1, 3, 5, 7, 9])
Out[-] 1 a 3 b 5 c 7 d 9 e dtype: object
pd.Series(data, index=[1, 3, 5, 7, 9])[1:4] # 묵시적인 인덱스만 따름
Out[-] 3 b 5 c 7 d dtype: object
pd.Series(data, index=[1, 3, 5, 7, 9]).loc[1:4] # 명시적인 인덱스만 따름
Out[-] 1 a 3 b dtype: object
pd.Series(data, index=[1, 3, 5, 7, 9]).iloc[1:4] # 묵시적인 인덱스만 따름
Out[-] 3 b 5 c 7 d dtype: object
 

결측값(NaN, None) 처리

  1. NaN
      • 자료형이 Float
      • 배열에서 연산할 경우 오류가 발생하지 않지만 결과값이 NaN이 됨
  1. None
      • 자료형이 None
      • 배열 연산을 할 경우 오류가 발생
3. 처리방법
  • isnull() : 결측값 확인 (결측 이면 True , 결측이 아니면 False )
  • notnull() : 결측값 확인 (결측 이면 False , 결측이 아니면 True )
  • dropna() : 결측값을 삭제
  • fillna(Num) : 결측을 Num 으로 채워 넣음
data = [1, 2, 3, None] print(np.array(data)) # None - 수치연산 시 error print(pd.Series(data)) # NaN - 수치연산 처리가 용이
Out[-] [1 2 3 None] 0 1.0 1 2.0 2 3.0 3 NaN dtype: float64
print(pd.Series(data)[3] + 100) print(pd.Series(data)[3] * 100) print(pd.Series(data)[3] * 0)
Out[-] nan nan nan
s = pd.Series(data) print(s) print(s.sum()) print(s.max()) print(s.min())
Out[-] 0 1.0 1 2.0 2 3.0 3 NaN dtype: float64 6.0 3.0 1.0
s.isnull()
Out[-] 0 False 1 False 2 False 3 True dtype: bool
data = [1, 2, 3, None, None, None, None] s = pd.Series(data) print(s.isnull()) print(s.isnull().sum())
Out[-] 0 False 1 False 2 False 3 True 4 True 5 True 6 True dtype: bool 4
print(s.notnull()) print(s.notnull().sum())
Out[-] 0 True 1 True 2 True 3 False 4 False 5 False 6 False dtype: bool 3
s.dropna()
Out[-] 0 1.0 1 2.0 2 3.0 dtype: float64
s.fillna(0)
Out[-] 0 1.0 1 2.0 2 3.0 3 0.0 4 0.0 5 0.0 6 0.0 dtype: float64
 

multiIndex

매출 = { '2015년':1000000, '2016년':2000000, '2017년':3000000, '2018년':4000000, '2019년':11000000, '2020년':30000000, } 순익 = { '2015년':100001, '2016년':200001, '2017년':300001, '2018년':400001, '2019년':1100001, '2020년':3000001, }
indexOne = list(zip(['매출' for i in range(len(매출.keys()))], 매출.keys())) indexTwo = list(zip(['순익' for i in range(len(순익.keys()))], 순익.keys())) index = indexOne + indexTwo index
Out[-] [('매출', '2015년'), ('매출', '2016년'), ('매출', '2017년'), ('매출', '2018년'), ('매출', '2019년'), ('매출', '2020년'), ('순익', '2015년'), ('순익', '2016년'), ('순익', '2017년'), ('순익', '2018년'), ('순익', '2019년'), ('순익', '2020년')]
index = pd.MultiIndex.from_tuples(index) index
Out[-] MultiIndex([('매출', '2015년'), ('매출', '2016년'), ('매출', '2017년'), ('매출', '2018년'), ('매출', '2019년'), ('매출', '2020년'), ('순익', '2015년'), ('순익', '2016년'), ('순익', '2017년'), ('순익', '2018년'), ('순익', '2019년'), ('순익', '2020년')], )
값 = list(매출.values()) + list(순익.values()) # 더하기를 하려면 list로 변환해야 한다. print(매출.values()) print(순익.values()) print(값)
Out[-] dict_values([1000000, 2000000, 3000000, 4000000, 11000000, 30000000]) dict_values([100001, 200001, 300001, 400001, 1100001, 3000001]) [1000000, 2000000, 3000000, 4000000, 11000000, 30000000, 100001, 200001, 300001, 400001, 1100001, 3000001]
result = pd.Series(값, index=index) result
Out[-] 매출 2015년 1000000 2016년 2000000 2017년 3000000 2018년 4000000 2019년 11000000 2020년 30000000 순익 2015년 100001 2016년 200001 2017년 300001 2018년 400001 2019년 1100001 2020년 3000001 dtype: int64
print(result['매출'].sum()) print(result['순익'][-3:].sum())
Out[-] 51000000 4500003
result['순익'][-3:]
Out[-] 2018년 400001 2019년 1100001 2020년 3000001 dtype: int64
 

연산 함수

  • add : 더하기 연산 함수
  • sub : 빼기 연산 함수
  • mul : 곱하기 연산 함수
  • floordiv : 나누었을 때 몫을 구하는 함수
  • div : 나누기 연산 함수
  • mod : 나머지 구하는 연산 함수
  • pow : 거듭제곱 연산 함수
s = pd.Series([100, 200, 300, 400, 500]) ss = pd.Series([10, 20, 30, 40, 50])
s + 100
Out[-] 0 200 1 300 2 400 3 500 4 600 dtype: int64
s.add(100)
Out[-] 0 200 1 300 2 400 3 500 4 600 dtype: int64
s + ss
Out[-] 0 110 1 220 2 330 3 440 4 550 dtype: int64
s.add(ss)
Out[-] 0 110 1 220 2 330 3 440 4 550 dtype: int64
s - ss
Out[-] 0 90 1 180 2 270 3 360 4 450 dtype: int64
s.sub(ss)
Out[-] 0 90 1 180 2 270 3 360 4 450 dtype: int64
s * ss
Out[-] 0 1000 1 4000 2 9000 3 16000 4 25000 dtype: int64
s.mul(ss)
Out[-] 0 1000 1 4000 2 9000 3 16000 4 25000 dtype: int64
s // ss # integer형
Out[-] 0 10 1 10 2 10 3 10 4 10 dtype: int64
s / ss # float형
Out[-] 0 10.0 1 10.0 2 10.0 3 10.0 4 10.0 dtype: float64
s.floordiv(ss)
Out[-] 0 10 1 10 2 10 3 10 4 10 dtype: int64
s.div(ss)
Out[-] 0 10.0 1 10.0 2 10.0 3 10.0 4 10.0 dtype: float64
s % ss
Out[-] 0 0 1 0 2 0 3 0 4 0 dtype: int64
s.mod(ss)
Out[-] 0 0 1 0 2 0 3 0 4 0 dtype: int64
s.mod(3)
Out[-] 0 1 1 2 2 0 3 1 4 2 dtype: int64
s
Out[-] 0 100 1 200 2 300 3 400 4 500 dtype: int64
s ** 3
Out[-] 0 1000000 1 8000000 2 27000000 3 64000000 4 125000000 dtype: int64
s.pow(3)
Out[-] 0 1000000 1 8000000 2 27000000 3 64000000 4 125000000 dtype: int64
 

집계 함수

  • count : 데이터 개수 구하는 함수
  • min : 최소값 구하는 함수
  • max : 최대값 구하는 함수
  • mean : 평균 구하는 함수
  • median : 중앙값 구하는 함수
  • std : 표준편차 구하는 함수
  • var : 분산 구하는 함수
  • mad : 절대 표준편차 구하는 함수
  • describe : 기초 통계를 한 번에 볼 수 있는 함수
s.count()
Out[-] 5
print(s.min()) print(s.max()) print(s.mean()) print(s.median()) print(s.sum()) print(s.std()) print(s.var()) print(s.mad())
Out[-] 100 500 300.0 300.0 1500 158.11388300841898 25000.0 120.0
s.describe()
Out[-] count 5.000000 mean 300.000000 std 158.113883 min 100.000000 25% 200.000000 50% 300.000000 75% 400.000000 max 500.000000 dtype: float64
s.head(3)
Out[-] 0 100 1 200 2 300 dtype: int64
s.tail(3)
Out[-] 2 300 3 400 4 500 dtype: int64
 

데이터 결합

  • concat : 데이터 프레임끼리 결합
    • verify_integrity=True일 때, 인덱스의 중복이 존재하면 error 출력
    • ignore_index : 기존의 인덱스를 무시하고 차례대로 인덱스 출력
    • join='inner' : 결합하는 데이터들의 공통 부분만 출력
    • join='outer' : 결합하는 데이터들의 모든 값 출력
※ concatenate : 배열끼리 결합
import numpy as np a = np.arange(10).reshape(2, 5) b = np.arange(10).reshape(2, 5) c = np.arange(10).reshape(2, 5) a
Out[-] array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
np.concatenate([a, b, c])
Out[-] array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
np.concatenate([a, b, c], axis=1)
Out[-] array([[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9]])
import pandas as pd a = pd.Series(['A', 'B', 'C', 'D', 'E'], index=range(1, 6)) b = pd.Series(['A', 'B', 'C', 'D', 'E'], index=range(1, 6)) c = pd.Series(['A', 'B', 'C', 'D', 'E'], index=range(1, 6)) a
Out[-] 1 A 2 B 3 C 4 D 5 E dtype: object
np.concatenate([a, b, c])
Out[-] array(['A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'], dtype=object)
pd.concat([a, b, c])
Out[-] 1 A 2 B 3 C 4 D 5 E 1 A 2 B 3 C 4 D 5 E 1 A 2 B 3 C 4 D 5 E dtype: object
pd.concat([a, b, c])[5]
Out[-] 5 E 5 E 5 E dtype: object
pd.concat([a, b, c], verify_integrity=False)
Out[-] 1 A 2 B 3 C 4 D 5 E 1 A 2 B 3 C 4 D 5 E 1 A 2 B 3 C 4 D 5 E dtype: object
d = pd.concat([a, b, c], verify_integrity=False, ignore_index=True, copy=False, axis=1) print(type(d)) print(d)
Out[-] <class 'pandas.core.frame.DataFrame'> 0 1 2 1 A A A 2 B B B 3 C C C 4 D D D 5 E E E
a.append(b)
Out[-] 1 A 2 B 3 C 4 D 5 E 1 A 2 B 3 C 4 D 5 E dtype: object
a = pd.Series(['A', 'B', 'C', 'D', 'E', 'F'], index=range(1, 7)) b = pd.Series(['A', 'B', 'C', 'D', 'E'], index=range(1, 6)) c = pd.Series(['A', 'B', 'C', 'D', 'E'], index=range(1, 6)) d = pd.concat([a, b, c], axis=1) print(type(d)) print(d)
Out[-] <class 'pandas.core.frame.DataFrame'> 0 1 2 1 A A A 2 B B B 3 C C C 4 D D D 5 E E E 6 F NaN NaN
pd.concat([a, b, c], axis=1, join='inner')
Out[-] 0 1 2 1 A A A 2 B B B 3 C C C 4 D D D 5 E E E
pd.concat([a, b, c], axis=1, join='outer')
Out[-] 0 1 2 1 A A A 2 B B B 3 C C C 4 D D D 5 E E E 6 F NaN NaN
 

DataFrame

  • 다차원 배열(Series의 특성을 가지고 있는 2차원 배열)
  • 가장 기본적인 데이터 구조
연차 연도 매출 순익 직원수 1 2015 1000000 100001 1 2 2016 2000000 200001 2 3 2017 3000000 300001 4 4 2018 4000000 400001 8 5 2019 8000000 800001 16 6 2020 16000000 1600001 32
rawData = { '연차':[1, 2, 3, 4, 5, 6], '연도':[2015, 2016, 2017, 2018, 2019, 2020], '매출':[1000000, 2000000, 3000000, 4000000, 8000000, 16000000], '순익':[100001, 200001, 300001, 400001, 800001, 1600001], '직원수':[1, 2, 4, 8, 16, 32] } pd.DataFrame(rawData)
Out[-] 연차 연도 매출 순익 직원수 0 1 2015 1000000 100001 1 1 2 2016 2000000 200001 2 2 3 2017 3000000 300001 4 3 4 2018 4000000 400001 8 4 5 2019 8000000 800001 16 5 6 2020 16000000 1600001 32
pd.DataFrame(rawData)['연도']
Out[-] 0 2015 1 2016 2 2017 3 2018 4 2019 5 2020 Name: 연도, dtype: int64
pd.DataFrame(rawData).iloc[0:3]
Out[-] 연차 연도 매출 순익 직원수 0 1 2015 1000000 100001 1 1 2 2016 2000000 200001 2 2 3 2017 3000000 300001 4
pd.DataFrame(rawData).iloc[-3:]
Out[-] 연차 연도 매출 순익 직원수 3 4 2018 4000000 400001 8 4 5 2019 8000000 800001 16 5 6 2020 16000000 1600001 32
pd.DataFrame(rawData, columns=['연차','매출','순익','직원수'], index=rawData['연도'])
Out[-] 연차 매출 순익 직원수 2015 1 1000000 100001 1 2016 2 2000000 200001 2 2017 3 3000000 300001 4 2018 4 4000000 400001 8 2019 5 8000000 800001 16 2020 6 16000000 1600001 32
%%writefile rawData.csv 1, 2, 3, 4, 5, 6, 7 연차,1, 2, 3, 4, 5, 6 연도,2015, 2016, 2017, 2018, 2019, 2020 매출,1000000, 2000000, 3000000, 4000000, 8000000, 16000000 순익,100001, 200001, 300001, 400001, 800001, 1600001 직원수,1, 2, 4, 8, 16, 32
pd.read_csv('rawData.csv')
Out[-] 1 2 3 4 5 6 7 0 연차 1 2 3 4 5 6 1 연도 2015 2016 2017 2018 2019 2020 2 매출 1000000 2000000 3000000 4000000 8000000 16000000 3 순익 100001 200001 300001 400001 800001 1600001 4 직원수 1 2 4 8 16 32
pd.read_csv('rawData.csv').columns
Out[-] Index(['1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7'], dtype='object')
pd.read_csv('rawData.csv').index
Out[-] RangeIndex(start=0, stop=5, step=1)
 

DataFrame에 데이터 조작

  • np.nan : NaN으로 값을 채움
  • drop : 컬럼 삭제
    • inplace = True : drop후 원본에 반영
  • pd.to_numeric() : 문자형을 숫자형으로 변환
import pandas as pd rawData = { '연차':[1, 2, 3, 4, 5, 6], '연도':[2015, 2016, 2017, 2018, 2019, 2020], '매출':[1000000, 2000000, 3000000, 4000000, 8000000, 16000000], '순익':[100001, 200001, 300001, 400001, 800001, 1600001], '직원수':[1, 2, 4, 8, 16, 32] } df = pd.DataFrame(rawData) df
Out[-] 연차 연도 매출 순익 직원수 0 1 2015 1000000 100001 1 1 2 2016 2000000 200001 2 2 3 2017 3000000 300001 4 3 4 2018 4000000 400001 8 4 5 2019 8000000 800001 16 5 6 2020 16000000 1600001 32
df['매출'] df.매출
Out[-] 0 1000000 1 2000000 2 3000000 3 4000000 4 8000000 5 16000000 Name: 매출, dtype: int64
df['순이익율'] = (df['순익'] / df['매출']) * 100 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000 100001 1 10.000100 1 2 2016 2000000 200001 2 10.000050 2 3 2017 3000000 300001 4 10.000033 3 4 2018 4000000 400001 8 10.000025 4 5 2019 8000000 800001 16 10.000013 5 6 2020 16000000 1600001 32 10.000006
df['test'] = 100 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 test 0 1 2015 1000000 100001 1 10.000100 100 1 2 2016 2000000 200001 2 10.000050 100 2 3 2017 3000000 300001 4 10.000033 100 3 4 2018 4000000 400001 8 10.000025 100 4 5 2019 8000000 800001 16 10.000013 100 5 6 2020 16000000 1600001 32 10.000006 100
import numpy as np df['testTwo'] = np.nan df
Out[-] 연차 연도 매출 순익 직원수 순이익율 test testTwo 0 1 2015 1000000 100001 1 10.000100 100 NaN 1 2 2016 2000000 200001 2 10.000050 100 NaN 2 3 2017 3000000 300001 4 10.000033 100 NaN 3 4 2018 4000000 400001 8 10.000025 100 NaN 4 5 2019 8000000 800001 16 10.000013 100 NaN 5 6 2020 16000000 1600001 32 10.000006 100 NaN
df['testThree'] = None df
Out[-] 연차 연도 매출 순익 직원수 순이익율 test testTwo testThree 0 1 2015 1000000 100001 1 10.000100 100 NaN None 1 2 2016 2000000 200001 2 10.000050 100 NaN None 2 3 2017 3000000 300001 4 10.000033 100 NaN None 3 4 2018 4000000 400001 8 10.000025 100 NaN None 4 5 2019 8000000 800001 16 10.000013 100 NaN None 5 6 2020 16000000 1600001 32 10.000006 100 NaN None
df[['test', 'testTwo', 'testThree']] = 1000 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 test testTwo testThree 0 1 2015 1000000 100001 1 10.000100 1000 1000 1000 1 2 2016 2000000 200001 2 10.000050 1000 1000 1000 2 3 2017 3000000 300001 4 10.000033 1000 1000 1000 3 4 2018 4000000 400001 8 10.000025 1000 1000 1000 4 5 2019 8000000 800001 16 10.000013 1000 1000 1000 5 6 2020 16000000 1600001 32 10.000006 1000 1000 1000
del df['test'] df
Out[-] 연차 연도 매출 순익 직원수 순이익율 testTwo testThree 0 1 2015 1000000 100001 1 10.000100 1000 1000 1 2 2016 2000000 200001 2 10.000050 1000 1000 2 3 2017 3000000 300001 4 10.000033 1000 1000 3 4 2018 4000000 400001 8 10.000025 1000 1000 4 5 2019 8000000 800001 16 10.000013 1000 1000 5 6 2020 16000000 1600001 32 10.000006 1000 1000
df.drop(['testTwo'], axis='columns', inplace=True) df
Out[-] 연차 연도 매출 순익 직원수 순이익율 testThree 0 1 2015 1000000 100001 1 10.000100 1000 1 2 2016 2000000 200001 2 10.000050 1000 2 3 2017 3000000 300001 4 10.000033 1000 3 4 2018 4000000 400001 8 10.000025 1000 4 5 2019 8000000 800001 16 10.000013 1000 5 6 2020 16000000 1600001 32 10.000006 1000
df.drop(['testThree'], axis='columns', inplace=True) df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000 100001 1 10.000100 1 2 2016 2000000 200001 2 10.000050 2 3 2017 3000000 300001 4 10.000033 3 4 2018 4000000 400001 8 10.000025 4 5 2019 8000000 800001 16 10.000013 5 6 2020 16000000 1600001 32 10.000006
df.drop(df.columns[[0, 2]], axis='columns')
Out[-] 연도 순익 직원수 순이익율 0 2015 100001 1 10.000100 1 2016 200001 2 10.000050 2 2017 300001 4 10.000033 3 2018 400001 8 10.000025 4 2019 800001 16 10.000013 5 2020 1600001 32 10.000006
df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000 100001 1 10.000100 1 2 2016 2000000 200001 2 10.000050 2 3 2017 3000000 300001 4 10.000033 3 4 2018 4000000 400001 8 10.000025 4 5 2019 8000000 800001 16 10.000013 5 6 2020 16000000 1600001 32 10.000006
dfTwo = pd.DataFrame(np.array([[7, 2021, 160000000, 16000001, 60]]), columns=['연차','연도','매출','순익','직원수']).append(df, ignore_index=True) # dfTwo.ndim dfTwo
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 7 2021 160000000 16000001 60 NaN 1 1 2015 1000000 100001 1 10.000100 2 2 2016 2000000 200001 2 10.000050 3 3 2017 3000000 300001 4 10.000033 4 4 2018 4000000 400001 8 10.000025 5 5 2019 8000000 800001 16 10.000013 6 6 2020 16000000 1600001 32 10.000006
dfTwo.drop([0], inplace=True) dfTwo
Out[-] 연차 연도 매출 순익 직원수 순이익율 1 1 2015 1000000 100001 1 10.000100 2 2 2016 2000000 200001 2 10.000050 3 3 2017 3000000 300001 4 10.000033 4 4 2018 4000000 400001 8 10.000025 5 5 2019 8000000 800001 16 10.000013 6 6 2020 16000000 1600001 32 10.000006
df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000 100001 1 10.000100 1 2 2016 2000000 200001 2 10.000050 2 3 2017 3000000 300001 4 10.000033 3 4 2018 4000000 400001 8 10.000025 4 5 2019 8000000 800001 16 10.000013 5 6 2020 16000000 1600001 32 10.000006
df[df.매출 > 5000000]
Out[-] 연차 연도 매출 순익 직원수 순이익율 4 5 2019 8000000 800001 16 10.000013 5 6 2020 16000000 1600001 32 10.000006
# df[df.매출 > 5000000, ['순익', '직원수']] Error df.loc[df.매출 > 5000000, ['순익', '직원수']]
Out[-] 순익 직원수 4 800001 16 5 1600001 32
df[df.직원수 > 10]['순익'] - 10000
Out[-] 4 790001 5 1590001 Name: 순익, dtype: int64
df['순익'] = df[df.직원수 > 10]['순익'] - 10000 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000 NaN 1 10.000100 1 2 2016 2000000 NaN 2 10.000050 2 3 2017 3000000 NaN 4 10.000033 3 4 2018 4000000 NaN 8 10.000025 4 5 2019 8000000 790001.0 16 10.000013 5 6 2020 16000000 1590001.0 32 10.000006
rawData = { '연차':[1, 2, 3, 4, 5, 6], '연도':[2015, 2016, 2017, 2018, 2019, 2020], '매출':[1000000, 2000000, 3000000, 4000000, 8000000, 16000000], '순익':[100001, 200001, 300001, 400001, 800001, 1600001], '직원수':[1, 2, 4, 8, 16, 32] } df = pd.DataFrame(rawData) df['순익'] = np.where(df['직원수'] > 10, df['순익'] - 10000, df['순익']) df
Out[-] 연차 연도 매출 순익 직원수 0 1 2015 1000000 100001 1 1 2 2016 2000000 200001 2 2 3 2017 3000000 300001 4 3 4 2018 4000000 400001 8 4 5 2019 8000000 790001 16 5 6 2020 16000000 1590001 32
df.loc[6] = df.loc[5] * 2 df
Out[-] 연차 연도 매출 순익 직원수 0 1 2015 1000000 100001 1 1 2 2016 2000000 200001 2 2 3 2017 3000000 300001 4 3 4 2018 4000000 400001 8 4 5 2019 8000000 790001 16 5 6 2020 16000000 1590001 32 6 12 4040 32000000 3180002 64
df['순이익율'] = (df['순익'] / df['매출'])*100 df.loc[6] = df.loc[5] * 2 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1.0 2015.0 1000000.0 100001.0 1.0 10.000100 1 2.0 2016.0 2000000.0 200001.0 2.0 10.000050 2 3.0 2017.0 3000000.0 300001.0 4.0 10.000033 3 4.0 2018.0 4000000.0 400001.0 8.0 10.000025 4 5.0 2019.0 8000000.0 790001.0 16.0 9.875012 5 6.0 2020.0 16000000.0 1590001.0 32.0 9.937506 6 12.0 4040.0 32000000.0 3180002.0 64.0 19.875013
df['연도'][6] = 2021 df['연차'][6] = 7 df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1.0 2015.0 1000000.0 100001.0 1.0 10.000100 1 2.0 2016.0 2000000.0 200001.0 2.0 10.000050 2 3.0 2017.0 3000000.0 300001.0 4.0 10.000033 3 4.0 2018.0 4000000.0 400001.0 8.0 10.000025 4 5.0 2019.0 8000000.0 790001.0 16.0 9.875012 5 6.0 2020.0 16000000.0 1590001.0 32.0 9.937506 6 7.0 2021.0 32000000.0 3180002.0 64.0 19.875013
df.dtypes
Out[-] 연차 float64 연도 float64 매출 float64 순익 float64 직원수 float64 순이익율 float64 dtype: object
df['연차'] = df['연차'].astype('int') df['연도'] = df['연도'].astype('int') df
Out[-] 연차 연도 매출 순익 직원수 순이익율 0 1 2015 1000000.0 100001.0 1.0 10.000100 1 2 2016 2000000.0 200001.0 2.0 10.000050 2 3 2017 3000000.0 300001.0 4.0 10.000033 3 4 2018 4000000.0 400001.0 8.0 10.000025 4 5 2019 8000000.0 790001.0 16.0 9.875012 5 6 2020 16000000.0 1590001.0 32.0 9.937506 6 7 2021 32000000.0 3180002.0 64.0 19.875013
pd.Series([1, '2', '3', 'hojun', True, 10.1])
Out[-] 0 1 1 2 2 3 3 hojun 4 True 5 10.1 dtype: object
pd.to_numeric(pd.Series([1, '2', '3', 'hojun', True, 10.1]), errors='ignore')
Out[-] 0 1 1 2 2 3 3 hojun 4 True 5 10.1 dtype: object
pd.to_numeric(pd.Series([1, '2', '3', 'hojun', True, 10.1]), errors='coerce') # errors='coerce' : error를 결측치로 만듬
Out[-] 0 1.0 1 2.0 2 3.0 3 NaN 4 1.0 5 10.1 dtype: float64
 

MultiIndex

import numpy as np print(np.random.rand(4, 2)) # 0부터 1사이, 균일 분포, Matrix 생성 print(np.random.randint(10)) # 0부터 9사이, 숫자 1개 생성 print(np.random.randint(10, 20, size=10)) print(np.random.randint(10, 20, size=(3, 5))) print(np.random.randn(4, 2)) # 가우시안 표준 정규분포, Matrix 생성 print(np.unique([1, 1, 1, 2, 2, 3])) # 중복된 값 제거 print(np.random.choice(10, 5, replace=False)) # 5개만 선택, replace는 중복허락함
Out[-] [[0.84378258 0.74200548] [0.55837495 0.69908872] [0.85818263 0.56343036] [0.90647635 0.77013871]] 5 [16 16 16 13 18 14 11 16 10 19] [[11 14 10 17 13] [10 13 14 19 15] [14 15 12 12 17]] [[ 0.67612663 -0.52565421] [ 0.70822562 0.52063027] [ 0.23706617 0.74834107] [-0.16540672 -0.62646096]] [1 2 3] [4 1 6 3 9]
import pandas as pd df = pd.DataFrame(np.random.randint(50, 100, size=(4, 3)), index=[['1학년', '1학년', '2학년', '2학년'], ['1반', '2반', '1반', '2반']], columns=['국', '영', '수']) df
Out[-] 국 영 수 1학년 1반 77 83 60 2반 94 54 92 2학년 1반 81 70 75 2반 65 99 52
df = pd.DataFrame(np.random.randint(50, 100, size=(4, 3))) df
Out[-] 0 1 2 0 63 66 82 1 65 65 78 2 52 52 88 3 50 73 74
df.index
Out[-] RangeIndex(start=0, stop=4, step=1)
df.index = ['1반', '2반', '1반', '2반'] df
Out[-] 0 1 2 1반 63 66 82 2반 65 65 78 1반 52 52 88 2반 50 73 74
df.columns
Out[-] RangeIndex(start=0, stop=3, step=1)
df.columns = ['국', '영', '수'] df
Out[-] 국 영 수 1반 63 66 82 2반 65 65 78 1반 52 52 88 2반 50 73 74
df.index = [['1학년', '1학년', '2학년', '2학년'], ['1반', '2반', '1반', '2반']] df
Out[-] 국 영 수 1학년 1반 63 66 82 2반 65 65 78 2학년 1반 52 52 88 2반 50 73 74
df.columns = [['언어', '언어', '수리'],['국', '영', '수']] df
Out[-] 언어 수리 국 영 수 1학년 1반 63 66 82 2반 65 65 78 2학년 1반 52 52 88 2반 50 73 74
df['언어']
Out[-] 국 영 1학년 1반 63 66 2반 65 65 2학년 1반 52 52 2반 50 73
df['수리']
Out[-] 수 1학년 1반 82 2반 78 2학년 1반 88 2반 74
df['언어']['국']
Out[-] 1학년 1반 63 2반 65 2학년 1반 52 2반 50 Name: 국, dtype: int32
df.loc['1학년']
Out[-] 언어 수리 국 영 수 1반 63 66 82 2반 65 65 78
df.loc['1학년', '1반']
Out[-] 언어 국 63 영 66 수리 수 82 Name: (1학년, 1반), dtype: int32
df.index = [['제주고', '제주고', '제주고', '제주고'], ['1학년', '1학년', '2학년', '2학년'], ['1반', '2반', '1반', '2반']] df
Out[-] 언어 수리 국 영 수 제주고 1학년 1반 63 66 82 2반 65 65 78 2학년 1반 52 52 88 2반 50 73 7