In [120]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json as j
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
In [2]:
def aryInfo(ary) :
print('type - ', type(ary))
print('shape - ', ary.shape)
print('ndim -', ary.ndim)
print('dtype -', ary.dtype)
print('data - ')
print(ary)
def seriesInfo(s) :
print('type - ', type(s))
print('index - ', s.index)
print('value - ', s.values)
print('dtype -', s.dtype)
print()
print('data - ')
print(s)
- DataFrame(표 형식 - 행, 열) , .csv 파일을 읽어서 변환
- 행 인덱스, 열 인덱스
- pd.DataFrame(data = , index = , columns =)
In [18]:
print('dict를 이용한 프레임 생성 - ')
frm = pd.DataFrame({
'feature01' : [1,2,3],
'feature02' : [1,2,3],
'feature03' : [1,2,3]
})
#col을 기준으로 프레임을 만든다! , 인덱스 형식을 만들땐 딕셔너리가 보편적으로 많이 사용된다! (키 -> 인덱스)
print('type - ',type(frm))
print('shape - ', frm.shape)
print('ndim -', frm.ndim)
print('row idx - ', frm.index, type(frm.index))
print('col idx - ', frm.columns , type(frm.columns))
print('values - ',type(frm.values))
print(frm.values)
print('data - ')
display(frm)
def frmInfo(frm) :
print('type - ',type(frm))
print('shape - ', frm.shape)
print('ndim -', frm.ndim)
print('row idx - ', frm.index, type(frm.index))
print('col idx - ', frm.columns , type(frm.columns))
print('values - ',type(frm.values))
print(frm.values)
print('data - ')
display(frm)
dict를 이용한 프레임 생성 - type - <class 'pandas.core.frame.DataFrame'> shape - (3, 3) ndim - 2 row idx - RangeIndex(start=0, stop=3, step=1) <class 'pandas.core.indexes.range.RangeIndex'> col idx - Index(['feature01', 'feature02', 'feature03'], dtype='object') <class 'pandas.core.indexes.base.Index'> values - <class 'numpy.ndarray'> [[1 1 1] [2 2 2] [3 3 3]] data -
feature01 | feature02 | feature03 | |
---|---|---|---|
0 | 1 | 1 | 1 |
1 | 2 | 2 | 2 |
2 | 3 | 3 | 3 |
In [25]:
print('list 이용한 프레임 생성 -') #리스트 형식은 row로 들어간다, 데이터 입력하는 순서가 중요!
frm = pd.DataFrame(data = [['섭섭해','m',True],['동아대','m',False]],
columns = ['이름','성별','결혼여부'],
index = ['user_' + str(idx) for idx in range(2)])
frm
list 이용한 프레임 생성 -
Out[25]:
이름 | 성별 | 결혼여부 | |
---|---|---|---|
user_0 | 섭섭해 | m | True |
user_1 | 동아대 | m | False |
In [36]:
print('pre - processing(전처리) - 열 이름변경, rename()')
print('rename(columns | index = {old_columns : new:columns} , inplace = )') #inplace : 원본에 적용할것인지
print('컬럼명을 영문으로 변경한다면 - ')
frm.rename(columns = {'이름' : 'name', '성별' : 'gender', '결혼여부':'marriage'}, inplace= True,
index = {'user_0' : 'customer_0', 'user_1' : 'customer_1'})
print('index - ', frm.index)
print('columns - ', frm.columns)
print()
#for idx in frm.columns :
# print(idx)
pre - processing(전처리) - 열 이름변경, rename() rename(columns | index = {old_columns : new:columns} , inplace = ) 컬럼명을 영문으로 변경한다면 - index - Index(['customer_0', 'customer_1'], dtype='object') columns - Index(['name', 'gender', 'marriage'], dtype='object')
Out[36]:
name | gender | marriage | |
---|---|---|---|
customer_0 | 섭섭해 | m | True |
customer_1 | 동아대 | m | False |
In [47]:
print('데이터 추출 -')
print('indexing - \n ', frm['name'] , type( frm['name'])) #행인덱스는 안된다, 프레임은 시리즈로 구성되어있다
데이터 추출 - indexing - customer_0 섭섭해 customer_1 동아대 Name: name, dtype: object <class 'pandas.core.series.Series'>
In [49]:
print('데이터 추가 -')
frm['age'] = [10,20]
frm
데이터 추가 -
Out[49]:
name | gender | marriage | age | |
---|---|---|---|---|
customer_0 | 섭섭해 | m | True | 10 |
customer_1 | 동아대 | m | False | 20 |
In [50]:
print('열 삭제 - ')
del frm['age']
#del frm[['name','marriage']]
열 삭제 -
In [51]:
frm
Out[51]:
name | gender | marriage | |
---|---|---|---|
customer_0 | 섭섭해 | m | True |
customer_1 | 동아대 | m | False |
In [56]:
print('만약, 행 인덱싱을 하고싶다면 ? - 정답 : 무조건 슬라이싱')
print('정수라벨, 문자라벨 모두 가능')
print('정수 인덱싱은 -1, 문자 인덱싱은 해당 인덱스를 포함한다')
print(frm[ 0 : 1 ])
print(frm[ : 'customer_0' ])
만약, 행 인덱싱을 하고싶다면 ? - 정답 : 무조건 슬라이싱 정수라벨, 문자라벨 모두 가능 정수 인덱싱은 -1, 문자 인덱싱은 해당 인덱스를 포함한다 name gender marriage customer_0 섭섭해 m True name gender marriage customer_0 섭섭해 m True
In [62]:
frm['name'][: 'customer_0'] #시리즈에 슬라이스
print(frm['name'])
print(frm['name']['customer_0'], type(frm['name']['customer_0']))
print(frm['name'][ : 'customer_0'], type(frm['name'][ : 'customer_0']))
customer_0 섭섭해 customer_1 동아대 Name: name, dtype: object 섭섭해 <class 'str'> customer_0 섭섭해 Name: name, dtype: object <class 'pandas.core.series.Series'>
- json 데이터 프레임 생성
In [68]:
import urllib
url = 'http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20120101'
response = urllib.request.urlopen(url)
#print(response.read())
result = j.loads(response.read())
print('type - ' , type(result))
print('keys - ', result.keys())
type - <class 'dict'> keys - dict_keys(['boxOfficeResult'])
In [72]:
data = result['boxOfficeResult']['dailyBoxOfficeList']
data
Out[72]:
[{'rnum': '1', 'rank': '1', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20112207', 'movieNm': '미션임파서블:고스트프로토콜', 'openDt': '2011-12-15', 'salesAmt': '2776060500', 'salesShare': '36.3', 'salesInten': '-415699000', 'salesChange': '-13', 'salesAcc': '40541108500', 'audiCnt': '353274', 'audiInten': '-60106', 'audiChange': '-14.5', 'audiAcc': '5328435', 'scrnCnt': '697', 'showCnt': '3223'}, {'rnum': '2', 'rank': '2', 'rankInten': '1', 'rankOldAndNew': 'OLD', 'movieCd': '20110295', 'movieNm': '마이 웨이', 'openDt': '2011-12-21', 'salesAmt': '1189058500', 'salesShare': '15.6', 'salesInten': '-105894500', 'salesChange': '-8.2', 'salesAcc': '13002897500', 'audiCnt': '153501', 'audiInten': '-16465', 'audiChange': '-9.7', 'audiAcc': '1739543', 'scrnCnt': '588', 'showCnt': '2321'}, {'rnum': '3', 'rank': '3', 'rankInten': '-1', 'rankOldAndNew': 'OLD', 'movieCd': '20112621', 'movieNm': '셜록홈즈 : 그림자 게임', 'openDt': '2011-12-21', 'salesAmt': '1176022500', 'salesShare': '15.4', 'salesInten': '-210328500', 'salesChange': '-15.2', 'salesAcc': '10678327500', 'audiCnt': '153004', 'audiInten': '-31283', 'audiChange': '-17', 'audiAcc': '1442861', 'scrnCnt': '360', 'showCnt': '1832'}, {'rnum': '4', 'rank': '4', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20113260', 'movieNm': '퍼펙트 게임', 'openDt': '2011-12-21', 'salesAmt': '644532000', 'salesShare': '8.4', 'salesInten': '-75116500', 'salesChange': '-10.4', 'salesAcc': '6640940000', 'audiCnt': '83644', 'audiInten': '-12225', 'audiChange': '-12.8', 'audiAcc': '895416', 'scrnCnt': '396', 'showCnt': '1364'}, {'rnum': '5', 'rank': '5', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20113271', 'movieNm': '프렌즈: 몬스터섬의비밀 ', 'openDt': '2011-12-29', 'salesAmt': '436753500', 'salesShare': '5.7', 'salesInten': '-89051000', 'salesChange': '-16.9', 'salesAcc': '1523037000', 'audiCnt': '55092', 'audiInten': '-15568', 'audiChange': '-22', 'audiAcc': '202909', 'scrnCnt': '290', 'showCnt': '838'}, {'rnum': '6', 'rank': '6', 'rankInten': '1', 'rankOldAndNew': 'OLD', 'movieCd': '19940256', 'movieNm': '라이온 킹', 'openDt': '1994-07-02', 'salesAmt': '507115500', 'salesShare': '6.6', 'salesInten': '-114593500', 'salesChange': '-18.4', 'salesAcc': '1841625000', 'audiCnt': '45750', 'audiInten': '-11699', 'audiChange': '-20.4', 'audiAcc': '171285', 'scrnCnt': '244', 'showCnt': '895'}, {'rnum': '7', 'rank': '7', 'rankInten': '-1', 'rankOldAndNew': 'OLD', 'movieCd': '20113381', 'movieNm': '오싹한 연애', 'openDt': '2011-12-01', 'salesAmt': '344871000', 'salesShare': '4.5', 'salesInten': '-107005500', 'salesChange': '-23.7', 'salesAcc': '20634684500', 'audiCnt': '45062', 'audiInten': '-15926', 'audiChange': '-26.1', 'audiAcc': '2823060', 'scrnCnt': '243', 'showCnt': '839'}, {'rnum': '8', 'rank': '8', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20112709', 'movieNm': '극장판 포켓몬스터 베스트 위시「비크티니와 백의 영웅 레시라무」', 'openDt': '2011-12-22', 'salesAmt': '167809500', 'salesShare': '2.2', 'salesInten': '-45900500', 'salesChange': '-21.5', 'salesAcc': '1897120000', 'audiCnt': '24202', 'audiInten': '-7756', 'audiChange': '-24.3', 'audiAcc': '285959', 'scrnCnt': '186', 'showCnt': '348'}, {'rnum': '9', 'rank': '9', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20113311', 'movieNm': '앨빈과 슈퍼밴드3', 'openDt': '2011-12-15', 'salesAmt': '137030000', 'salesShare': '1.8', 'salesInten': '-35408000', 'salesChange': '-20.5', 'salesAcc': '3416675000', 'audiCnt': '19729', 'audiInten': '-6461', 'audiChange': '-24.7', 'audiAcc': '516289', 'scrnCnt': '169', 'showCnt': '359'}, {'rnum': '10', 'rank': '10', 'rankInten': '0', 'rankOldAndNew': 'OLD', 'movieCd': '20112708', 'movieNm': '극장판 포켓몬스터 베스트 위시 「비크티니와 흑의 영웅 제크로무」', 'openDt': '2011-12-22', 'salesAmt': '125535500', 'salesShare': '1.6', 'salesInten': '-40756000', 'salesChange': '-24.5', 'salesAcc': '1595695000', 'audiCnt': '17817', 'audiInten': '-6554', 'audiChange': '-26.9', 'audiAcc': '235070', 'scrnCnt': '175', 'showCnt': '291'}]
돌발퀴즈
- rnum, movieNm, salesAmt
- 위 세가지 값을 추출하여 데이터프레임을 만들어보자
- 컬럼명 변경 - 랭킹, 영화제목, 판매금액
In [81]:
movieFrm = pd.DataFrame(data)
movieFrm
Out[81]:
rnum | rank | rankInten | rankOldAndNew | movieCd | movieNm | openDt | salesAmt | salesShare | salesInten | salesChange | salesAcc | audiCnt | audiInten | audiChange | audiAcc | scrnCnt | showCnt | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 1 | 0 | OLD | 20112207 | 미션임파서블:고스트프로토콜 | 2011-12-15 | 2776060500 | 36.3 | -415699000 | -13 | 40541108500 | 353274 | -60106 | -14.5 | 5328435 | 697 | 3223 |
1 | 2 | 2 | 1 | OLD | 20110295 | 마이 웨이 | 2011-12-21 | 1189058500 | 15.6 | -105894500 | -8.2 | 13002897500 | 153501 | -16465 | -9.7 | 1739543 | 588 | 2321 |
2 | 3 | 3 | -1 | OLD | 20112621 | 셜록홈즈 : 그림자 게임 | 2011-12-21 | 1176022500 | 15.4 | -210328500 | -15.2 | 10678327500 | 153004 | -31283 | -17 | 1442861 | 360 | 1832 |
3 | 4 | 4 | 0 | OLD | 20113260 | 퍼펙트 게임 | 2011-12-21 | 644532000 | 8.4 | -75116500 | -10.4 | 6640940000 | 83644 | -12225 | -12.8 | 895416 | 396 | 1364 |
4 | 5 | 5 | 0 | OLD | 20113271 | 프렌즈: 몬스터섬의비밀 | 2011-12-29 | 436753500 | 5.7 | -89051000 | -16.9 | 1523037000 | 55092 | -15568 | -22 | 202909 | 290 | 838 |
5 | 6 | 6 | 1 | OLD | 19940256 | 라이온 킹 | 1994-07-02 | 507115500 | 6.6 | -114593500 | -18.4 | 1841625000 | 45750 | -11699 | -20.4 | 171285 | 244 | 895 |
6 | 7 | 7 | -1 | OLD | 20113381 | 오싹한 연애 | 2011-12-01 | 344871000 | 4.5 | -107005500 | -23.7 | 20634684500 | 45062 | -15926 | -26.1 | 2823060 | 243 | 839 |
7 | 8 | 8 | 0 | OLD | 20112709 | 극장판 포켓몬스터 베스트 위시「비크티니와 백의 영웅 레시라무」 | 2011-12-22 | 167809500 | 2.2 | -45900500 | -21.5 | 1897120000 | 24202 | -7756 | -24.3 | 285959 | 186 | 348 |
8 | 9 | 9 | 0 | OLD | 20113311 | 앨빈과 슈퍼밴드3 | 2011-12-15 | 137030000 | 1.8 | -35408000 | -20.5 | 3416675000 | 19729 | -6461 | -24.7 | 516289 | 169 | 359 |
9 | 10 | 10 | 0 | OLD | 20112708 | 극장판 포켓몬스터 베스트 위시 「비크티니와 흑의 영웅 제크로무」 | 2011-12-22 | 125535500 | 1.6 | -40756000 | -24.5 | 1595695000 | 17817 | -6554 | -26.9 | 235070 | 175 | 291 |
In [88]:
movie = pd.DataFrame(movieFrm[['rnum', 'movieNm', 'salesAmt']])
movie
movie.rename(columns = {'rnum' : '랭킹', 'movieNm' : '영화제목', 'salesAmt':'판매금액'}, inplace= True)
movie
Out[88]:
랭킹 | 영화제목 | 판매금액 | |
---|---|---|---|
0 | 1 | 미션임파서블:고스트프로토콜 | 2776060500 |
1 | 2 | 마이 웨이 | 1189058500 |
2 | 3 | 셜록홈즈 : 그림자 게임 | 1176022500 |
3 | 4 | 퍼펙트 게임 | 644532000 |
4 | 5 | 프렌즈: 몬스터섬의비밀 | 436753500 |
5 | 6 | 라이온 킹 | 507115500 |
6 | 7 | 오싹한 연애 | 344871000 |
7 | 8 | 극장판 포켓몬스터 베스트 위시「비크티니와 백의 영웅 레시라무」 | 167809500 |
8 | 9 | 앨빈과 슈퍼밴드3 | 137030000 |
9 | 10 | 극장판 포켓몬스터 베스트 위시 「비크티니와 흑의 영웅 제크로무」 | 125535500 |
In [99]:
print('case 02 -')
lst = []
for row in data :
lst.append([row['rnum'], row['movieNm'], row['salesAmt']])
print(lst)
movieFrm = pd.DataFrame(lst)
movieFrm.rename(columns = {0 : '랭킹', 1 : '영화제목', 2 :'판매금액'}, inplace= True)
display(movieFrm)
case 02 - [['1', '미션임파서블:고스트프로토콜', '2776060500'], ['2', '마이 웨이', '1189058500'], ['3', '셜록홈즈 : 그림자 게임', '1176022500'], ['4', '퍼펙트 게임', '644532000'], ['5', '프렌즈: 몬스터섬의비밀 ', '436753500'], ['6', '라이온 킹', '507115500'], ['7', '오싹한 연애', '344871000'], ['8', '극장판 포켓몬스터 베스트 위시「비크티니와 백의 영웅 레시라무」', '167809500'], ['9', '앨빈과 슈퍼밴드3', '137030000'], ['10', '극장판 포켓몬스터 베스트 위시 「비크티니와 흑의 영웅 제크로무」', '125535500']]
랭킹 | 영화제목 | 판매금액 | |
---|---|---|---|
0 | 1 | 미션임파서블:고스트프로토콜 | 2776060500 |
1 | 2 | 마이 웨이 | 1189058500 |
2 | 3 | 셜록홈즈 : 그림자 게임 | 1176022500 |
3 | 4 | 퍼펙트 게임 | 644532000 |
4 | 5 | 프렌즈: 몬스터섬의비밀 | 436753500 |
5 | 6 | 라이온 킹 | 507115500 |
6 | 7 | 오싹한 연애 | 344871000 |
7 | 8 | 극장판 포켓몬스터 베스트 위시「비크티니와 백의 영웅 레시라무」 | 167809500 |
8 | 9 | 앨빈과 슈퍼밴드3 | 137030000 |
9 | 10 | 극장판 포켓몬스터 베스트 위시 「비크티니와 흑의 영웅 제크로무」 | 125535500 |
- 데이터 조작(잘 꺼내야된다!!)
- 프레임은 기본 열 인덱스를 사용하고, 행 인덱스를 위해서는 슬라이싱
- loc[] 라벨값 , iloc[] 정수값 : 인덱서
In [87]:
#frm = pd.DataFrame(np.random.normal(50,2,(3,4)))
frm = pd.DataFrame(np.arange(100, 112).reshape(3,4), index = ['row_' + str(idx) for idx in range(1,4)],
columns =['feature_' + str(idx) for idx in range(1,5)] )
frm
Out[87]:
feature_1 | feature_2 | feature_3 | feature_4 | |
---|---|---|---|---|
row_1 | 100 | 101 | 102 | 103 |
row_2 | 104 | 105 | 106 | 107 |
row_3 | 108 | 109 | 110 | 111 |
In [88]:
frm.describe()
Out[88]:
feature_1 | feature_2 | feature_3 | feature_4 | |
---|---|---|---|---|
count | 3.0 | 3.0 | 3.0 | 3.0 |
mean | 104.0 | 105.0 | 106.0 | 107.0 |
std | 4.0 | 4.0 | 4.0 | 4.0 |
min | 100.0 | 101.0 | 102.0 | 103.0 |
25% | 102.0 | 103.0 | 104.0 | 105.0 |
50% | 104.0 | 105.0 | 106.0 | 107.0 |
75% | 106.0 | 107.0 | 108.0 | 109.0 |
max | 108.0 | 109.0 | 110.0 | 111.0 |
In [89]:
frm.info()
<class 'pandas.core.frame.DataFrame'> Index: 3 entries, row_1 to row_3 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 feature_1 3 non-null int32 1 feature_2 3 non-null int32 2 feature_3 3 non-null int32 3 feature_4 3 non-null int32 dtypes: int32(4) memory usage: 72.0+ bytes
In [90]:
print('인덱스 사용 - loc[] ')
#frm[] - 열인덱스
print('라벨값 기반 - ', frm.loc['row_1'].values) #행인덱스
print('정수값 기반 - ', frm.iloc[0].values)
print('멀티인덱스 [] \n- ', frm.loc[['row_1','row_3']])
print('슬라이싱 [] \n- ', frm.loc['row_1':'row_3'])
print('멀티인덱스 [] \n- ', frm.iloc[[0,2]])
print('슬라이싱 [] \n- ', frm.iloc[0:3])
인덱스 사용 - loc[] 라벨값 기반 - [100 101 102 103] 정수값 기반 - [100 101 102 103] 멀티인덱스 [] - feature_1 feature_2 feature_3 feature_4 row_1 100 101 102 103 row_3 108 109 110 111 슬라이싱 [] - feature_1 feature_2 feature_3 feature_4 row_1 100 101 102 103 row_2 104 105 106 107 row_3 108 109 110 111 멀티인덱스 [] - feature_1 feature_2 feature_3 feature_4 row_1 100 101 102 103 row_3 108 109 110 111 슬라이싱 [] - feature_1 feature_2 feature_3 feature_4 row_1 100 101 102 103 row_2 104 105 106 107 row_3 108 109 110 111
In [91]:
frm.loc[frm['feature_2'].values > 105 ]
Out[91]:
feature_1 | feature_2 | feature_3 | feature_4 | |
---|---|---|---|---|
row_3 | 108 | 109 | 110 | 111 |
In [92]:
print('행, 열 - ') #frm[열][행], frm.loc, frm.iloc[행,열]
print('첫번째 행의 모든 열을 추출하고싶다면 - iloc, loc')
print(frm.iloc[0,0:3])
print(frm.loc['row_1', 'feature_1':'feature_4'])
행, 열 - 첫번째 행의 모든 열을 추출하고싶다면 - iloc, loc feature_1 100 feature_2 101 feature_3 102 Name: row_1, dtype: int32 feature_1 100 feature_2 101 feature_3 102 feature_4 103 Name: row_1, dtype: int32
In [93]:
print('새로운 행을 추가 - ')
frm.loc['row_4'] = 200
frm
새로운 행을 추가 -
Out[93]:
feature_1 | feature_2 | feature_3 | feature_4 | |
---|---|---|---|---|
row_1 | 100 | 101 | 102 | 103 |
row_2 | 104 | 105 | 106 | 107 |
row_3 | 108 | 109 | 110 | 111 |
row_4 | 200 | 200 | 200 | 200 |
In [94]:
frm.loc['row_5'] = frm.loc['row_4']
frm
Out[94]:
feature_1 | feature_2 | feature_3 | feature_4 | |
---|---|---|---|---|
row_1 | 100 | 101 | 102 | 103 |
row_2 | 104 | 105 | 106 | 107 |
row_3 | 108 | 109 | 110 | 111 |
row_4 | 200 | 200 | 200 | 200 |
row_5 | 200 | 200 | 200 | 200 |
In [95]:
scores = {
'kor' : [90,85,100,77,78] ,
'eng' : [67,56,100,68,40],
'math' : [30,67,49,50,90],
}
frm = pd.DataFrame(scores, index = ['김채아','오세헌','임정섭','전진호','박영빈'])
frm
Out[95]:
kor | eng | math | |
---|---|---|---|
김채아 | 90 | 67 | 30 |
오세헌 | 85 | 56 | 67 |
임정섭 | 100 | 100 | 49 |
전진호 | 77 | 68 | 50 |
박영빈 | 78 | 40 | 90 |
In [96]:
print('Q1. 모든 학생의 과목평균 점수를 새로운 열 추가')
frm['mean'] = np.mean(frm.values, axis=1).round(2)
frm
Q1. 모든 학생의 과목평균 점수를 새로운 열 추가
Out[96]:
kor | eng | math | mean | |
---|---|---|---|---|
김채아 | 90 | 67 | 30 | 62.33 |
오세헌 | 85 | 56 | 67 | 69.33 |
임정섭 | 100 | 100 | 49 | 83.00 |
전진호 | 77 | 68 | 50 | 65.00 |
박영빈 | 78 | 40 | 90 | 69.33 |
In [97]:
print('Q2. 오세헌 학생의 영어점수를 90점으로 수정하고 평균 점수도 다시 계산')
frm.loc['오세헌','eng']=90
frm
Q2. 오세헌 학생의 영어점수를 90점으로 수정하고 평균 점수도 다시 계산
Out[97]:
kor | eng | math | mean | |
---|---|---|---|---|
김채아 | 90 | 67 | 30 | 62.33 |
오세헌 | 85 | 90 | 67 | 69.33 |
임정섭 | 100 | 100 | 49 | 83.00 |
전진호 | 77 | 68 | 50 | 65.00 |
박영빈 | 78 | 40 | 90 | 69.33 |
In [98]:
print('Q3. 전진호 학생의 점수를 데이터프레임으로 추출')
frm.loc[['전진호']]
Q3. 전진호 학생의 점수를 데이터프레임으로 추출
Out[98]:
kor | eng | math | mean | |
---|---|---|---|---|
전진호 | 77 | 68 | 50 | 65.0 |
In [99]:
print('Q4. 김채아 학생의 점수를 시리즈로 추출')
pd.Series(frm.loc['김채아']) #frm.loc['김채아']
Q4. 김채아 학생의 점수를 시리즈로 추출
Out[99]:
kor 90.00 eng 67.00 math 30.00 mean 62.33 Name: 김채아, dtype: float64
In [100]:
print('Q5. 박영빈 학생의 국어,수학점수를 95점으로 수정하고 평균 점수도 다시 계산 ')
frm.loc['박영빈','kor'] = 95
frm.loc['박영빈','math'] = 95
frm['mean'] = np.mean(frm[['kor','eng','math']], axis = 1).round(2)
frm
Q5. 박영빈 학생의 국어,수학점수를 95점으로 수정하고 평균 점수도 다시 계산
Out[100]:
kor | eng | math | mean | |
---|---|---|---|---|
김채아 | 90 | 67 | 30 | 62.33 |
오세헌 | 85 | 90 | 67 | 80.67 |
임정섭 | 100 | 100 | 49 | 83.00 |
전진호 | 77 | 68 | 50 | 65.00 |
박영빈 | 95 | 40 | 95 | 76.67 |
In [101]:
titanicFrm = sns.load_dataset('titanic')
print('type - ', type(titanicFrm))
titanicFrm
type - <class 'pandas.core.frame.DataFrame'>
Out[101]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
886 | 0 | 2 | male | 27.0 | 0 | 0 | 13.0000 | S | Second | man | True | NaN | Southampton | no | True |
887 | 1 | 1 | female | 19.0 | 0 | 0 | 30.0000 | S | First | woman | False | B | Southampton | yes | True |
888 | 0 | 3 | female | NaN | 1 | 2 | 23.4500 | S | Third | woman | False | NaN | Southampton | no | False |
889 | 1 | 1 | male | 26.0 | 0 | 0 | 30.0000 | C | First | man | True | C | Cherbourg | yes | True |
890 | 0 | 3 | male | 32.0 | 0 | 0 | 7.7500 | Q | Third | man | True | NaN | Queenstown | no | True |
891 rows × 15 columns
In [102]:
titanicFrm.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category 12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool dtypes: bool(2), category(2), float64(2), int64(4), object(5) memory usage: 80.7+ KB
In [112]:
print('선실등급의 인원 수를 확인하고 싶다면 - ')
titanicFrm['pclass'].value_counts().values
선실등급의 인원 수를 확인하고 싶다면 -
Out[112]:
array([491, 216, 184], dtype=int64)
In [104]:
print('프레임의 컬럼명을 확인하고 싶다면 -')
titanicFrm.columns
프레임의 컬럼명을 확인하고 싶다면 -
Out[104]:
Index(['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone'], dtype='object')
In [105]:
print('Q1) age_by_10 컬럼을 추가하고 싶다(기존나이에 10살을 더한 값을) ')
titanicFrm['age_by_10'] = ((titanicFrm['age'] + 10).values).astype('int')
titanicFrm.head()
Q1) age_by_10 컬럼을 추가하고 싶다(기존나이에 10살을 더한 값을)
Out[105]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | age_by_10 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False | 32 |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False | 48 |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True | 36 |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False | 45 |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True | 45 |
In [106]:
print('Q2) parch와 sibsp 더한값에 1을 추가해서 family_no 컬럼추가')
titanicFrm['family_no'] = titanicFrm['parch'] + titanicFrm['sibsp'] + 1
titanicFrm.head()
Q2) parch와 sibsp 더한값에 1을 추가해서 family_no 컬럼추가
Out[106]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | age_by_10 | family_no | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False | 32 | 2 |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False | 48 | 2 |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True | 36 | 1 |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False | 45 | 2 |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True | 45 | 1 |
In [107]:
print('Q3) 방금 만든 2개의 컬럼을 삭제하고 싶다면 - ')
print('drop( , axis = 1 )')
titanicFrm.drop(['age_by_10' , 'family_no'] , axis = 1 , inplace = True)
Q3) 방금 만든 2개의 컬럼을 삭제하고 싶다면 - drop( , axis = 1 )
In [108]:
titanicFrm.head()
Out[108]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True |
In [109]:
print('Q4) 요금(fare)에 대한 통계(최대, 최소, 평균, 합계) 확인이 필요하다 - ')
print('sum - ' , np.sum(titanicFrm['fare'].values))
Q4) 요금(fare)에 대한 통계(최대, 최소, 평균, 합계) 확인이 필요하다 - sum - 28693.9493
In [110]:
print('Q5) 선실등급이 3 등급인 데이터만의 subset 만들어라 - ')
pclassFrm = titanicFrm[ titanicFrm['pclass'] == 3 ]
pclassFrm
Q5) 선실등급이 3 등급인 데이터만의 subset 만들어라 -
Out[110]:
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True |
5 | 0 | 3 | male | NaN | 0 | 0 | 8.4583 | Q | Third | man | True | NaN | Queenstown | no | True |
7 | 0 | 3 | male | 2.0 | 3 | 1 | 21.0750 | S | Third | child | False | NaN | Southampton | no | False |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
882 | 0 | 3 | female | 22.0 | 0 | 0 | 10.5167 | S | Third | woman | False | NaN | Southampton | no | True |
884 | 0 | 3 | male | 25.0 | 0 | 0 | 7.0500 | S | Third | man | True | NaN | Southampton | no | True |
885 | 0 | 3 | female | 39.0 | 0 | 5 | 29.1250 | Q | Third | woman | False | NaN | Queenstown | no | False |
888 | 0 | 3 | female | NaN | 1 | 2 | 23.4500 | S | Third | woman | False | NaN | Southampton | no | False |
890 | 0 | 3 | male | 32.0 | 0 | 0 | 7.7500 | Q | Third | man | True | NaN | Queenstown | no | True |
491 rows × 15 columns
In [111]:
print('Q6) 선실등급이 3 등급인 데이터의 subset 만들고 sex, who 데이터만 추출 - ')
# pclassFrm[['sex', 'who']]
pclassFrm.loc[ : , ['sex', 'who']]
Q6) 선실등급이 3 등급인 데이터의 subset 만들고 sex, who 데이터만 추출 -
Out[111]:
sex | who | |
---|---|---|
0 | male | man |
2 | female | woman |
4 | male | man |
5 | male | man |
7 | male | child |
... | ... | ... |
882 | female | woman |
884 | male | man |
885 | female | woman |
888 | female | woman |
890 | male | man |
491 rows × 2 columns
Q01) 다음 조건을 만족하는 임의의 데이터 프레임을 작성해 보자
조건) 열의 갯수와 행의 갯수가 각각 5개 이상이여야 한다. 조건) 열에는 정수, 문자, 실수, 날짜 데이터가 각각 1개이상 포함되어야 한다.
Q02) 제공된 booklist_json.json 파일로부터 데이터를 읽어 들여서 데이터 프레임을 작성해 보자
hint) numpy 파일 입출력
- json.loads() : json으로 된 문자열 파일을 읽어들일 때
- json.load() : json 파일을 읽어들일 때
In [139]:
df = pd.DataFrame(pd.read_json('./data/booklist_json.json'))
print(type(df))
display(df)
<class 'pandas.core.frame.DataFrame'>
bookName | link | |
---|---|---|
0 | 나는 꼭 필요한 것만 남기기로 했다 | http://www.hanbit.co.kr/store/books/look.php?p... |
1 | 파이썬과 대스크를 활용한 고성능 데이터 분석 | http://www.hanbit.co.kr/store/books/look.php?p... |
2 | 웹어셈블리 인 액션 | http://www.hanbit.co.kr/store/books/look.php?p... |
3 | 쉽게 배워 바로 써먹는 디자인 패턴 | http://www.hanbit.co.kr/store/books/look.php?p... |
4 | 부의 원칙 | http://www.hanbit.co.kr/store/books/look.php?p... |
5 | 만들면서 배우는 픽셀 아트 | http://www.hanbit.co.kr/store/books/look.php?p... |
6 | 초보자를 위한 언리얼 엔진 4 입문 | http://www.hanbit.co.kr/store/books/look.php?p... |
7 | 분산원장 기술 | http://www.hanbit.co.kr/store/books/look.php?p... |
8 | 회사에서 바로 통하는 3ds Max + V-Ray | http://www.hanbit.co.kr/store/books/look.php?p... |
9 | 재미있고 빠른 한글 쓰기 3권 : 교과서 쉬운 낱말 | http://www.hanbit.co.kr/store/books/look.php?p... |
10 | 나도 초록 식물 잘 키우면 소원이 없겠네 | http://www.hanbit.co.kr/store/books/look.php?p... |
11 | IT CookBook, 액세스 2019로 배우는 데이터베이스 기초와 실습 | http://www.hanbit.co.kr/store/books/look.php?p... |
12 | GAN 인 액션 | http://www.hanbit.co.kr/store/books/look.php?p... |
13 | 재미있고 빠른 어휘력 동화 – 아지랑이가 뭐야? | http://www.hanbit.co.kr/store/books/look.php?p... |
14 | 재미있고 빠른 어휘력 동화 – 많다의 반대가 뭐야? | http://www.hanbit.co.kr/store/books/look.php?p... |
15 | 만화로 보는 바빌론 부자들의 돈 버는 지혜 | http://www.hanbit.co.kr/store/books/look.php?p... |
16 | 포르잔 C++ 바이블 | http://www.hanbit.co.kr/store/books/look.php?p... |
17 | 청소년 인문학 수업 - 1권 | http://www.hanbit.co.kr/store/books/look.php?p... |
18 | 청소년 인문학 수업 - 2권 | http://www.hanbit.co.kr/store/books/look.php?p... |
19 | 처음 시작하는 파이썬(2판) | http://www.hanbit.co.kr/store/books/look.php?p... |
20 | 퀀트 전략을 위한 인공지능 트레이딩 | http://www.hanbit.co.kr/store/books/look.php?p... |
21 | 처음 시작하는 딥러닝 | http://www.hanbit.co.kr/store/books/look.php?p... |
22 | 회사에서 바로 통하는 실무 엑셀 매크로&VBA | http://www.hanbit.co.kr/store/books/look.php?p... |
23 | 게임 오버 | http://www.hanbit.co.kr/store/books/look.php?p... |
24 | 초소형 머신러닝 TinyML | http://www.hanbit.co.kr/store/books/look.php?p... |
25 | 오늘도 뇌는 거짓말을 한다 | http://www.hanbit.co.kr/store/books/look.php?p... |
26 | 허팝만 따라 해봐! 유튜브 정석 | http://www.hanbit.co.kr/store/books/look.php?p... |
27 | 이것이 취업을 위한 코딩 테스트다 with 파이썬 | http://www.hanbit.co.kr/store/books/look.php?p... |
28 | 딥러닝을 위한 선형대수학 | http://www.hanbit.co.kr/store/books/look.php?p... |
29 | 유닉스의 탄생 | http://www.hanbit.co.kr/store/books/look.php?p... |
30 | 회사에서 바로 통하는 오토캐드 AutoCAD 2021 | http://www.hanbit.co.kr/store/books/look.php?p... |
31 | IT CookBook, 오라클로 배우는 데이터베이스 개론과 실습(2판) | http://www.hanbit.co.kr/store/books/look.php?p... |
32 | 별, 걔 다 그립네 | http://www.hanbit.co.kr/store/books/look.php?p... |
33 | 대학을 버려야 대학이 산다 | http://www.hanbit.co.kr/store/books/look.php?p... |
34 | IT CookBook, 따라 하면서 배우는 사물인터넷 | http://www.hanbit.co.kr/store/books/look.php?p... |
35 | 재미있고 빠른 첫 한글 준비 선 긋기1권 직선∙곡선∙자음∙모음 | http://www.hanbit.co.kr/store/books/look.php?p... |
36 | 재미있고 빠른 첫 한글 4권 쌍자음∙받침 | http://www.hanbit.co.kr/store/books/look.php?p... |
37 | 핸즈온 비지도 학습 | http://www.hanbit.co.kr/store/books/look.php?p... |
38 | 재미있고 빠른 첫 한글 쓰기1권 모음∙자음∙쉬운 낱말 | http://www.hanbit.co.kr/store/books/look.php?p... |
39 | 우리 아이 처음 놀이 | http://www.hanbit.co.kr/store/books/look.php?p... |
40 | 미라클 모닝 기적의 공식(개정판) | http://www.hanbit.co.kr/store/books/look.php?p... |
41 | 창의적 공학설계(3판) | http://www.hanbit.co.kr/store/books/look.php?p... |
42 | R로 하는 다변량 데이터 분석 : 이론부터 실무 활용까지 | http://www.hanbit.co.kr/store/books/look.php?p... |
43 | 공학 핵심수학(2판) : 기초부터 심화까지 핵심만 쏙쏙 | http://www.hanbit.co.kr/store/books/look.php?p... |
44 | 응용이 보이는 선형대수학 : 파이썬과 함께하는 선형대수학 이론과 응용 | http://www.hanbit.co.kr/store/books/look.php?p... |
45 | 파이썬 증권 데이터 분석 | http://www.hanbit.co.kr/store/books/look.php?p... |
46 | 나의 첫 파이썬(2판) | http://www.hanbit.co.kr/store/books/look.php?p... |
47 | 나는 왜 네 말이 힘들까 | http://www.hanbit.co.kr/store/books/look.php?p... |
48 | 혼자 공부하는 첫 프로그래밍 with 파이썬 | http://www.hanbit.co.kr/store/books/look.php?p... |
49 | 퇴근길 인문학 수업 : 뉴노멀 | http://www.hanbit.co.kr/store/books/look.php?p... |
In [ ]:
'Language > Python' 카테고리의 다른 글
python_pandas_day04 (0) | 2023.09.25 |
---|---|
python_pandas_day03 (0) | 2023.09.25 |
python_pandas_day01 (0) | 2023.09.25 |
python_numpy_day03 (0) | 2023.09.25 |
python_numpy_day02 (0) | 2023.09.25 |