In [2]:
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/Datamanim/datarepo/main/youtube/youtube.csv", index_col='Unnamed: 0')
df
Out[2]:
| title | channelTitle | categoryId | view_count | likes | dislikes | comment_count | channelId | trending_date2 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | [신병] 물자창고 | 장삐쭈 | 23 | 1893473 | 38249 | 730 | 8595 | UChbE5OZQ6dRHECsX0tEPEZQ | 2021-01-01 |
| 1 | RAIN(비) - 나로 바꾸자 Switch to me (duet with JYP) MV | RAIN's Official Channel | 10 | 2600864 | 0 | 0 | 20129 | UCxXgIeE5hxWxHG6dz9Scg2w | 2021-01-01 |
| 2 | 2020년 제야의 종 온라인 타종행사 | 보신각 현장 행사는 진행하지 않습니다. | 서울시 · Seoul | 29 | 347049 | 3564 | 120 | 178 | UCZUPZW5idAxYp-Asj__lVAA | 2021-01-01 |
| 3 | 고기남자의 칠면조 파티 | 고기남자 MeatMan | 26 | 528458 | 15372 | 280 | 3470 | UCT3CumbFIJiW33uq0UI3zlg | 2021-01-01 |
| 4 | 골목 3mc를 분노하게 만든 마음고생이 심했을 공릉 백반집 사장님의 푸념?! [예능... | 스브스밥집 | 24 | 494904 | 3918 | 111 | 3142 | UCdWgRSfttvDucq4ApcCg5Mw | 2021-01-01 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 60394 | *풀코스로 먹습니다* 🍗치킨 + 🍕피자 + 🥧디저트 | 공룡 | 22 | 538190 | 16671 | 209 | 3117 | UCWf4QKgnTyvmehcRqw-JldQ | 2021-10-19 |
| 60395 | [놀면 뭐하니? 예고] 우린 깐부잖아🦑 놀뭐에 등장한 월드클래스 초대손님!! MBC... | 놀면 뭐하니? | 24 | 1607562 | 14615 | 258 | 1141 | UCx6jsZ02B4K3SECUrkgPyzg | 2021-10-19 |
| 60396 | 먹방 전쟁 : 사랑스러War (feat. 401 정육식당) | 김종국 GYM JONG KOOK | 17 | 1125911 | 26490 | 263 | 1915 | UCoe-0EVDJnjlSoPK8ygcGwQ | 2021-10-19 |
| 60397 | "너.. 광수지?" 협상에 거짓말부터 던지는 광수 닮은꼴 김연경 선수 [런닝맨|21... | 스브스 예능맛집 | 24 | 1741773 | 14994 | 304 | 802 | UCnx4Fi4cmkLGDiFfZ311wWw | 2021-10-19 |
| 60398 | ENHYPEN (엔하이픈) 'Tamed-Dashed' Official MV | HYBE LABELS | 10 | 13753485 | 1784532 | 9737 | 195461 | UC3IZKseVpdzPSBaWxBxundA | 2021-10-19 |
60399 rows × 9 columns
1. 인기동영상 제작횟수가 많은 채널 상위 10개명을 출력하라 (날짜기준, 중복포함)¶
In [3]:
ans = df.loc[df['channelId'].isin(df['channelId'].value_counts().head().index),'channelTitle'].unique()
print(list(ans))
['파뿌리', '짤툰', '런닝맨 - 스브스 공식 채널', '엠뚜루마뚜루 : MBC 공식 종합 채널', 'SPOTV']
2. 논란으로 인기동영상이 된 케이스를 확인하고 싶다. dislikes수가 like 수보다 높은 동영상을 제작한 채널을 모두 출력하라¶
In [4]:
ans = df.loc[df['dislikes'] > df['likes'],'channelTitle'].unique()
print(list(ans))
['핫도그TV', 'ASMR 애정TV', '하얀트리HayanTree', '양팡 YangPang', '철구형 (CHULTUBE)', '왜냐맨하우스', '(MUTUBE)와꾸대장봉준', '오메킴TV', '육지담', 'MapleStory_KR', 'ROAD FIGHTING CHAMPIONSHIP', '사나이 김기훈', '나혼자산다 STUDIO', 'Gen.G esports']
3. 채널명을 바꾼 케이스가 있는지 확인하고 싶다. channelId의 경우 고유값이므로 이를 통해 채널명을 한번이라도 바꾼 채널의 갯수를 구하여라¶
In [5]:
ans = df[['channelId','channelTitle']].drop_duplicates().channelId.value_counts()
ans = ans[ans>1]
print(len(ans))
71
4. 일요일에 인기있었던 영상들중 가장많은 영상 종류(categoryId)는 무엇인가?¶
In [6]:
df['trending_date2'] = pd.to_datetime(df['trending_date2'])
df['trending_date2'].dt.day_name()
ans = df.loc[df['trending_date2'].dt.day_name()=='Sunday'].categoryId.value_counts()
ans.index[0]
Out[6]:
24
In [7]:
df['trending_date2'].dt.day_name().unique()
Out[7]:
array(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday'], dtype=object)
5. 각 요일별 인기 영상들의 categoryId는 각각 몇개 씩인지 하나의 데이터 프레임으로 표현하라¶
In [8]:
df.pivot_table(index='categoryId', columns=df['trending_date2'].dt.day_name() , aggfunc='size')
Out[8]:
| trending_date2 | Friday | Monday | Saturday | Sunday | Thursday | Tuesday | Wednesday |
|---|---|---|---|---|---|---|---|
| categoryId | |||||||
| 1 | 243 | 263 | 255 | 274 | 246 | 257 | 234 |
| 2 | 120 | 105 | 119 | 99 | 128 | 119 | 129 |
| 10 | 833 | 837 | 776 | 830 | 890 | 894 | 917 |
| 15 | 187 | 215 | 198 | 217 | 207 | 208 | 207 |
| 17 | 633 | 668 | 592 | 636 | 682 | 708 | 706 |
| 19 | 90 | 92 | 87 | 91 | 92 | 89 | 85 |
| 20 | 283 | 298 | 296 | 289 | 282 | 285 | 291 |
| 22 | 1288 | 1373 | 1289 | 1337 | 1341 | 1375 | 1333 |
| 23 | 568 | 594 | 570 | 556 | 560 | 569 | 566 |
| 24 | 2976 | 3148 | 3066 | 3096 | 2954 | 3084 | 3090 |
| 25 | 444 | 453 | 422 | 437 | 470 | 452 | 468 |
| 26 | 369 | 378 | 364 | 363 | 375 | 394 | 385 |
| 27 | 183 | 205 | 183 | 199 | 194 | 194 | 212 |
| 28 | 171 | 160 | 173 | 167 | 166 | 161 | 165 |
| 29 | 12 | 10 | 10 | 9 | 13 | 11 | 12 |
6.댓글의 수로 (comment_count) 영상 반응에 대한 판단을 할 수 있다. viewcount대비 댓글수가 가장 높은 영상을 확인하라 (view_count값이 0인 경우는 제외한다)¶
In [60]:
target = df.loc[df['view_count']!=0]
target['ratio'] = target['comment_count']/target['view_count']
target.sort_values(by='ratio',ascending = False, inplace=True)
print(target.iloc[0,0])
60분 동안 댓글이 달리지 않으면, 영상이 삭제됩니다. (챌린지)
C:\Users\Public\Documents\ESTsoft\CreatorTemp/ipykernel_26476/4169578624.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy target['ratio'] = target['comment_count']/target['view_count']
7. 댓글의 수로 (comment_count) 영상 반응에 대한 판단을 할 수 있다.viewcount대비 댓글수가 가장 낮은 영상을 확인하라 (view_counts, ratio값이 0인경우는 제외한다.)¶
In [65]:
target['ratio'].value_counts()
target = target.loc[target['ratio']!=0]
target.sort_values(by='ratio', ascending=True, inplace=True)
print(target.iloc[0,0])
Join the BTS #PermissiontoDance Challenge only on YouTube #Shorts
8. like 대비 dislike의 수가 가장 적은 영상은 무엇인가? (like, dislike 값이 0인경우는 제외한다)¶
In [75]:
target = df.loc[(df['likes']!=0) & (df['dislikes']!=0)]
target['ratio'] = target['dislikes']/target['likes']
target.sort_values(by='ratio', ascending = True, inplace=True)
print(target.iloc[0,0])
[줌터뷰] *최초공개* 사부작즈🐰🐶의 비공식 이름은 아이라인즈? 꿀조합 티키타카 가득한 NCT 127 도영&정우의 줌터뷰
C:\Users\Public\Documents\ESTsoft\CreatorTemp/ipykernel_26476/812080242.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy target['ratio'] = target['dislikes']/target['likes']
9. 가장많은 트렌드 영상을 제작한 채널의 이름은 무엇인가? (날짜기준, 중복포함)¶
In [89]:
print(df.loc[df['channelId'] == df['channelId'].value_counts().index[0]].channelTitle.unique()[0])
짤툰
In [120]:
df['channelId'].value_counts() >=20
Out[120]:
UCszFjh7CEfwDb7UUGb4RzCQ True
UClzB2iZ5jPoTNz0S-QU6Wiw True
UCtm_QoN2SIxwCE-59shX7Qg True
UCaKod3X1Tn4c7Ci0iUKcvzQ True
UCiwQRG2sCcfjKkgxMEdJGPg True
...
UCj00eA-Q0lokXCA6JAa_grw False
UCdtY7-_h-KgBTXHJfTk8wwQ False
UCESC_GRUe4Z7-OOxk_AWm5Q False
UCGuE0TrBNIZKfordUwAQe2w False
UCNh_yWrspnQbZDZijQFyjbw False
Name: channelId, Length: 1770, dtype: bool
10. 20회(20일)이상 인기동영상 리스트에 포함된 동영상의 숫자는?¶
In [127]:
(df[['title','channelId']].value_counts() >= 20).sum()
Out[127]:
40
11. 각 데이터의 ‘ct’컬럼을 시간으로 인식할수 있게 datatype을 변경하고 video 데이터의 videoname의 각 value 마다 몇개의 데이터씩 가지고 있는지 확인하라¶
In [9]:
import pandas as pd
channel = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/youtube/channelInfo.csv')
video = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/youtube/videoInfo.csv')
display(channel.head(2))
display(video.head(2))
#datatype변경
channel['ct'] = pd.to_datetime(channel['ct'])
video['ct'] = pd.to_datetime(video['ct'])
print(video['videoname'].value_counts())
| channelid | subcnt | viewcnt | videocnt | ct | channelname | |
|---|---|---|---|---|---|---|
| 0 | UCkQCwnkQfgSuPTTnw_Y7v7w | 1310000 | 410238653 | 736 | 2021-09-30 03:01:03 | 꽈뚜룹 |
| 1 | UCkQCwnkQfgSuPTTnw_Y7v7w | 1310000 | 412531322 | 736 | 2021-09-30 09:01:03 | 꽈뚜룹 |
| videopk | viewcnt | likecnt | dislikecnt | favoritecnt | cmcnt | ct | videoname | |
|---|---|---|---|---|---|---|---|---|
| 0 | c5JQp6xafqc | 1667010 | 30474 | 706 | 0 | 6587 | 2021-10-10 15:20:03 | 공범 EP1 |
| 1 | c5JQp6xafqc | 1669089 | 30495 | 707 | 0 | 6589 | 2021-10-10 15:30:03 | 공범 EP1 |
공범 EP1 3492 공범 EP2 3204 공범 EP3 2568 공범 EP4 2280 공범 EP5 1562 공범 EP6 1274 공범 EP7 555 공범 EP8 266 Name: videoname, dtype: int64
12. 수집된 각 video의 가장 최신화 된 날짜의 viewcount값을 출력하라¶
In [24]:
target = video.sort_values(by=['ct','videoname'], ascending = True).drop_duplicates('videoname', keep='last')
target
Out[24]:
| videopk | viewcnt | likecnt | dislikecnt | favoritecnt | cmcnt | ct | videoname | |
|---|---|---|---|---|---|---|---|---|
| 3491 | c5JQp6xafqc | 3180532 | 41043 | 1113 | 0 | 7674 | 2021-11-01 15:30:03 | 공범 EP1 |
| 6695 | 23QQ1ru9YQg | 2199328 | 25566 | 763 | 0 | 9171 | 2021-11-01 15:30:03 | 공범 EP2 |
| 9263 | GygoAk1hDU0 | 1671294 | 22719 | 508 | 0 | 12499 | 2021-11-01 15:30:03 | 공범 EP3 |
| 11543 | bK0_3Vbfvs8 | 1818493 | 22703 | 408 | 0 | 16949 | 2021-11-01 15:30:03 | 공범 EP4 |
| 13105 | hv7FBjskAu0 | 1503435 | 19926 | 421 | 0 | 12434 | 2021-11-01 15:30:04 | 공범 EP5 |
| 14934 | AxGKHmXyuAE | 1750222 | 24494 | 389 | 0 | 13025 | 2021-11-01 15:30:04 | 공범 EP6 |
| 13660 | QUjQbgj5IXM | 1630200 | 29335 | 400 | 0 | 18247 | 2021-11-01 15:30:05 | 공범 EP7 |
| 15200 | yZt-h-KcmUE | 1289088 | 25616 | 3621 | 0 | 31663 | 2021-11-01 15:30:05 | 공범 EP8 |
13. Channel 데이터중 2021-10-03일 이후 각 채널의 처음 기록 됐던 구독자 수(subcnt)를 출력하라¶
In [46]:
target = channel.loc[channel['ct']> pd.to_datetime('2021-10-03')].sort_values('ct', ascending=True).drop_duplicates('channelname', keep='first')
target[['subcnt','channelname']].reset_index(drop=True)
Out[46]:
| subcnt | channelname | |
|---|---|---|
| 0 | 922000 | 논리왕 전기 |
| 1 | 322000 | 츄정ChuJeong |
| 2 | 257000 | 야전삽짱재 |
| 3 | 7520 | 김농밀의 농밀한 삶 |
| 4 | 55000 | 와글와글 WagleWagle |
| 5 | 10100 | 릴펄 Lilpearl |
| 6 | 14900 | 형사!탐정되다 |
| 7 | 215000 | 조나단 |
| 8 | 1330000 | 꽈뚜룹 |
| 9 | 54300 | Balming Tiger |
| 10 | 471000 | 곽토리 kwak tori |
14. 각채널의 2021-10-03 03:00:00 ~ 2021-11-01 15:00:00 까지 구독자수 (subcnt) 의 증가량을 구하여라¶
In [81]:
start = channel.loc[channel['ct'].dt.strftime('%Y-%m-%d %H')=='2021-10-03 03']
end = channel.loc[channel['ct'].dt.strftime('%Y-%m-%d %H')=='2021-11-01 15']
start = start[['channelname','subcnt']]
end = end[['channelname','subcnt']]
target = pd.merge(start, end, on='channelname', how='inner')
target['del'] = target['subcnt_y'] - target['subcnt_x']
#target[['channelname','del']]
Out[81]:
| channelname | del | |
|---|---|---|
| 0 | 꽈뚜룹 | 70000 |
| 1 | 야전삽짱재 | 11000 |
| 2 | 츄정ChuJeong | 1000 |
| 3 | 논리왕 전기 | -11000 |
| 4 | 와글와글 WagleWagle | 0 |
| 5 | 조나단 | 12000 |
| 6 | 형사!탐정되다 | 10300 |
| 7 | 김농밀의 농밀한 삶 | 1540 |
| 8 | 릴펄 Lilpearl | 11000 |
| 9 | 곽토리 kwak tori | -2000 |
| 10 | Balming Tiger | 2500 |
15. 각 비디오는 10분 간격으로 구독자수, 좋아요, 싫어요수, 댓글수가 수집된것으로 알려졌다. 공범 EP1의 비디오정보 데이터중 수집간격이 5분 이하, 20분이상인 데이터 구간( 해당 시점 전,후) 의 시각을 모두 출력하라¶
In [122]:
import datetime
target = video.loc[video['videoname'].str.contains('공범 EP1')].sort_values(by='ct')
#target = [(target.ct.diff(1)>=datetime.timedelta(minutes=20)) | (target.ct.diff(1)<=datetime.timedelta(minutes=5))]
target.loc[((target['ct'].diff(1)>=datetime.timedelta(minutes=20))==True) | ((target['ct'].diff(1)<=datetime.timedelta(minutes=5))==True)]
Out[122]:
| videopk | viewcnt | likecnt | dislikecnt | favoritecnt | cmcnt | ct | videoname | |
|---|---|---|---|---|---|---|---|---|
| 721 | c5JQp6xafqc | 2228250 | 34559 | 849 | 0 | 7191 | 2021-10-13 09:41:37 | 공범 EP1 |
| 722 | c5JQp6xafqc | 2228250 | 34559 | 849 | 0 | 7191 | 2021-10-13 09:41:37 | 공범 EP1 |
| 1636 | c5JQp6xafqc | 2707933 | 37901 | 988 | 0 | 7410 | 2021-10-19 18:20:03 | 공범 EP1 |
16. 각 에피소드의 시작날짜(년-월-일)를 에피소드 이름과 묶어 데이터 프레임으로 만들고 출력하라¶
In [133]:
target = video.sort_values(by='ct', ascending = True).drop_duplicates('videoname',keep='first')
target['date'] = target['ct'].dt.strftime('%Y-%m-%d')
target[['date','videoname']]
Out[133]:
| date | videoname | |
|---|---|---|
| 10 | 2021-10-07 | 공범 EP1 |
| 3496 | 2021-10-09 | 공범 EP2 |
| 6696 | 2021-10-14 | 공범 EP3 |
| 9264 | 2021-10-16 | 공범 EP4 |
| 11544 | 2021-10-21 | 공범 EP5 |
| 13661 | 2021-10-23 | 공범 EP6 |
| 13106 | 2021-10-28 | 공범 EP7 |
| 14935 | 2021-10-30 | 공범 EP8 |
17. “공범” 컨텐츠의 경우 19:00시에 공개 되는것으로 알려져있다. 공개된 날의 21시의 viewcnt, ct, videoname 으로 구성된 데이터 프레임을 viewcnt를 내림차순으로 정렬하여 출력하라¶
In [152]:
video['time'] = video['ct'].dt.hour
target = video.loc[video['time']==21].sort_values(by='ct', ascending=True).drop_duplicates('videoname', keep='first')
target = target.sort_values(by='viewcnt', ascending=False)[['videoname','viewcnt','ct']].reset_index(drop=True)
target
Out[152]:
| videoname | viewcnt | ct | |
|---|---|---|---|
| 0 | 공범 EP8 | 264029 | 2021-10-30 21:00:08 |
| 1 | 공범 EP7 | 252032 | 2021-10-28 21:00:04 |
| 2 | 공범 EP4 | 217674 | 2021-10-16 21:00:04 |
| 3 | 공범 EP6 | 213899 | 2021-10-23 21:00:06 |
| 4 | 공범 EP5 | 201179 | 2021-10-21 21:00:04 |
| 5 | 공범 EP2 | 148144 | 2021-10-09 21:00:03 |
| 6 | 공범 EP3 | 147183 | 2021-10-14 21:00:04 |
| 7 | 공범 EP1 | 117340 | 2021-10-07 21:00:03 |
18. video 정보의 가장 최근 데이터들에서 각 에피소드의 싫어요/좋아요 비율을 ratio 컬럼으로 만들고 videoname, ratio로 구성된 데이터 프레임을 ratio를 오름차순으로 정렬하라¶
In [159]:
target = video.sort_values(by='ct', ascending=True).drop_duplicates('videoname', keep='last')
target['ratio'] = target['dislikecnt'] / target['likecnt']
target = target.sort_values(by='ratio', ascending=True)[['videoname','ratio']].reset_index(drop=True)
target
Out[159]:
| videoname | ratio | |
|---|---|---|
| 0 | 공범 EP7 | 0.013636 |
| 1 | 공범 EP6 | 0.015881 |
| 2 | 공범 EP4 | 0.017971 |
| 3 | 공범 EP5 | 0.021128 |
| 4 | 공범 EP3 | 0.022360 |
| 5 | 공범 EP1 | 0.027118 |
| 6 | 공범 EP2 | 0.029844 |
| 7 | 공범 EP8 | 0.141357 |
19. 2021-11-01 00:00:00 ~ 15:00:00까지 각 에피소드별 viewcnt의 증가량을 데이터 프레임으로 만드시오¶
In [175]:
target = video.loc[(video['ct']>=pd.to_datetime('2021-11-01 00')) & (video['ct']<= pd.to_datetime('2021-11-01 15'))]
target = target.sort_values(by='ct', ascending = True)
start = target.drop_duplicates('videoname', keep='first')[['videoname','viewcnt']]
end = target.drop_duplicates('videoname', keep='last')[['videoname','viewcnt']]
#display(start)
#display(end)
target = pd.merge(start,end,on='videoname',how='inner')
target['viewcnt'] = target['viewcnt_y'] - target['viewcnt_x']
target = target[['videoname','viewcnt']].set_index('videoname')
target
Out[175]:
| viewcnt | |
|---|---|
| videoname | |
| 공범 EP1 | 13298 |
| 공범 EP2 | 10300 |
| 공범 EP3 | 9927 |
| 공범 EP6 | 14141 |
| 공범 EP4 | 9824 |
| 공범 EP5 | 10824 |
| 공범 EP8 | 89147 |
| 공범 EP7 | 26949 |
20. video 데이터 중에서 중복되는 데이터가 존재한다. 중복되는 각 데이터의 시간대와 videoname 을 구하여라¶
In [179]:
target = video.loc[video.index.isin(set(video.index)-set(video.drop_duplicates().index))]
target[['videoname','ct']]
Out[179]:
| videoname | ct | |
|---|---|---|
| 722 | 공범 EP1 | 2021-10-13 09:41:37 |
| 3927 | 공범 EP2 | 2021-10-13 09:41:37 |
21. 주어진 전체 기간의 각 나라별 골득점수 상위 5개 국가와 그 득점수를 데이터프레임형태로 출력하라¶
In [191]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/worldcup/worldcupgoals.csv')
df.head()
target = df.groupby('Country').sum().sort_values('Goals', ascending=False).head(5)
target
Out[191]:
| Goals | |
|---|---|
| Country | |
| Brazil | 228 |
| Germany | 226 |
| Argentina | 135 |
| Italy | 123 |
| France | 115 |
22. 주어진 전체기간동안 골득점을 한 선수가 가장 많은 나라 상위 5개 국가와 그 선수 숫자를 데이터 프레임 형식으로 출력하라¶
In [208]:
target = df.groupby('Country').size().sort_values(ascending=False).head(5)
target
Out[208]:
Country Brazil 81 Germany 78 Italy 60 Argentina 59 France 58 dtype: int64
23. Years 컬럼은 년도 -년도 형식으로 구성되어있고, 각 년도는 4자리 숫자이다. 년도 표기가 4자리 숫자로 안된 케이스가 존재한다. 해당 건은 몇건인지 출력하라¶
In [217]:
def solution(x):
str_list = x.split('-')
for i in str_list:
if len(i) != 4:
return True
else:
return False
df['check'] = df['Years'].apply(solution)
target = len(df.loc[df['check']== True])
target
Out[217]:
45
24. Q3에서 발생한 예외 케이스를 제외한 데이터프레임을 df2라고 정의하고 데이터의 행의 숫자를 출력하라¶
In [221]:
df2 = df.loc[df['check']==False]
len(df2)
Out[221]:
1250
25. 월드컵 출전횟수를 나타내는 ‘LenCup’ 컬럼을 추가하고 4회 출전한 선수의 숫자를 구하여라¶
In [233]:
df2['yearList'] = df2['Years'].str.split('-')
df2['LenCup'] = df2['yearList'].str.len()
#target = df2.loc[df2['LenCup']==4]
#print(len(target))
df2
C:\Users\Public\Documents\ESTsoft\CreatorTemp/ipykernel_31380/79792409.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df2['yearList'] = df2['Years'].str.split('-')
C:\Users\Public\Documents\ESTsoft\CreatorTemp/ipykernel_31380/79792409.py:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df2['LenCup'] = df2['yearList'].str.len()
Out[233]:
| Player | Goals | Years | Country | check | LenCup | yearList | |
|---|---|---|---|---|---|---|---|
| 0 | Miroslav Klose | 16 | 2002-2006-2010-2014 | Germany | False | 4 | [2002, 2006, 2010, 2014] |
| 1 | Ronaldo | 15 | 1998-2002-2006 | Brazil | False | 3 | [1998, 2002, 2006] |
| 2 | Gerd Muller | 14 | 1970-1974 | Germany | False | 2 | [1970, 1974] |
| 3 | Just Fontaine | 13 | 1958 | France | False | 1 | [1958] |
| 4 | Pele | 12 | 1958-1962-1966-1970 | Brazil | False | 4 | [1958, 1962, 1966, 1970] |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 1290 | Josip Skoblar | 1 | 1962 | Yugoslavia | False | 1 | [1962] |
| 1291 | Safet Susic | 1 | 1982-1990 | Yugoslavia | False | 2 | [1982, 1990] |
| 1292 | Aleksandar Tirnanic | 1 | 1930 | Yugoslavia | False | 1 | [1930] |
| 1293 | Djordje Vujadinovic | 1 | 1930 | Yugoslavia | False | 1 | [1930] |
| 1294 | Branko Zebec | 1 | 1954-1958 | Yugoslavia | False | 2 | [1954, 1958] |
1250 rows × 7 columns
26. Yugoslavia 국가의 월드컵 출전횟수가 2회인 선수들의 숫자를 구하여라¶
In [237]:
target = df2.loc[(df2['Country']=='Yugoslavia') & (df2['LenCup']==2)]
print(len(target))
7
27. 2002년도에 출전한 전체 선수는 몇명인가?¶
In [248]:
target = df2.loc[df2['Years'].str.contains('2002')]
print(len(target))
156
28. 이름에 ‘carlos’ 단어가 들어가는 선수의 숫자는 몇 명인가? (대, 소문자 구분 x)¶
In [262]:
target = df2.loc[df2['Player'].str.lower().str.contains('carlos')]
print(len(target))
13
29. 월드컵 출전 횟수가 1회뿐인 선수들 중에서 가장 많은 득점을 올렸던 선수는 누구인가?¶
In [268]:
target = df2.loc[df2['LenCup']==1].sort_values(by='Goals', ascending=False)
print(target.loc[3,'Player'])
Just Fontaine
30. 월드컵 출전횟수가 1회 뿐인 선수들이 가장 많은 국가는 어디인가?¶
In [278]:
target = df2.loc[df2['LenCup']==1].Country.value_counts().index[0]
target
Out[278]:
'Brazil'
In [269]:
df2
Out[269]:
| Player | Goals | Years | Country | check | LenCup | yearList | |
|---|---|---|---|---|---|---|---|
| 0 | Miroslav Klose | 16 | 2002-2006-2010-2014 | Germany | False | 4 | [2002, 2006, 2010, 2014] |
| 1 | Ronaldo | 15 | 1998-2002-2006 | Brazil | False | 3 | [1998, 2002, 2006] |
| 2 | Gerd Muller | 14 | 1970-1974 | Germany | False | 2 | [1970, 1974] |
| 3 | Just Fontaine | 13 | 1958 | France | False | 1 | [1958] |
| 4 | Pele | 12 | 1958-1962-1966-1970 | Brazil | False | 4 | [1958, 1962, 1966, 1970] |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 1290 | Josip Skoblar | 1 | 1962 | Yugoslavia | False | 1 | [1962] |
| 1291 | Safet Susic | 1 | 1982-1990 | Yugoslavia | False | 2 | [1982, 1990] |
| 1292 | Aleksandar Tirnanic | 1 | 1930 | Yugoslavia | False | 1 | [1930] |
| 1293 | Djordje Vujadinovic | 1 | 1930 | Yugoslavia | False | 1 | [1930] |
| 1294 | Branko Zebec | 1 | 1954-1958 | Yugoslavia | False | 2 | [1954, 1958] |
1250 rows × 7 columns
31. 대여일자별 데이터의 수를 데이터프레임으로 출력하고, 가장 많은 데이터가 있는 날짜를 출력하라¶
In [123]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/bicycle/seoul_bi.csv')
df.head()
Out[123]:
| 대여일자 | 대여시간 | 대여소번호 | 대여구분코드 | 성별 | 연령대코드 | 이용건수 | 운동량 | 탄소량 | 이동거리 | 사용시간 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2021-06-01 | 0 | 3541 | 정기권 | F | ~10대 | 1 | 0.00 | 0.00 | 0.00 | 8 |
| 1 | 2021-06-01 | 0 | 765 | 정기권 | F | ~10대 | 1 | 27.21 | 0.35 | 1526.81 | 19 |
| 2 | 2021-06-01 | 0 | 2637 | 정기권 | F | ~10대 | 1 | 41.40 | 0.37 | 1608.56 | 18 |
| 3 | 2021-06-01 | 0 | 2919 | 정기권 | F | ~10대 | 1 | 0.00 | 0.00 | 0.00 | 75 |
| 4 | 2021-06-01 | 0 | 549 | 정기권 | F | ~10대 | 1 | 13.04 | 0.17 | 731.55 | 6 |
In [2]:
target = df.groupby('대여일자').size().sort_values(ascending=False)
print(target.index[0])
2021-06-04
32. 각 일자의 요일을 표기하고 (‘Monday’ ~’Sunday’) ‘day_name’컬럼을 추가하고 이를 이용하여 각 요일별 이용 횟수의 총합을 데이터 프레임으로 출력하라¶
In [3]:
df['대여일자'] = pd.to_datetime(df['대여일자'])
df['day_name'] = df['대여일자'].dt.day_name()
target = df.groupby('day_name').size()
target = target.to_frame().sort_values(by=0, ascending=False)
target.rename(columns={0: 'count'}, inplace=True)
target
Out[3]:
| count | |
|---|---|
| day_name | |
| Wednesday | 110607 |
| Friday | 108877 |
| Monday | 107568 |
| Tuesday | 103704 |
| Saturday | 101299 |
| Sunday | 90918 |
| Thursday | 55977 |
33. 각 요일별 가장 많이 이용한 대여소의 이용횟수와 대여소 번호를 데이터 프레임으로 출력하라¶
In [4]:
target = df.groupby(['day_name','대여소번호']).size().to_frame('size').reset_index()
target.sort_values(by='size', ascending=False, inplace = True)
target= target.drop_duplicates('day_name', keep='first').reset_index(drop=True)
target
Out[4]:
| day_name | 대여소번호 | size | |
|---|---|---|---|
| 0 | Saturday | 502 | 378 |
| 1 | Sunday | 502 | 372 |
| 2 | Wednesday | 502 | 282 |
| 3 | Friday | 502 | 277 |
| 4 | Tuesday | 502 | 267 |
| 5 | Monday | 502 | 242 |
| 6 | Thursday | 2715 | 137 |
34. 나이대별 대여구분 코드의 (일일권/전체횟수) 비율을 구한 후 가장 높은 비율을 가지는 나이대를 확인하라. 일일권의 경우 일일권 과 일일권(비회원)을 모두 포함하라¶
In [5]:
target = df[['연령대코드','대여구분코드']].groupby('연령대코드').size().to_frame('total_count').reset_index()
target
target1 = df.loc[df['대여구분코드'].isin(['일일권','일일권(비회원)'])].groupby('연령대코드').size().to_frame('count').reset_index()
target1
end_target = pd.merge(target, target1, on='연령대코드', how='inner')
end_target['ratio'] = end_target['count']/end_target['total_count']
end_target.sort_values(by='ratio', ascending=False, inplace=True)
print(end_target.loc[6,'연령대코드'])
~10대
35. 연령대별 평균 이동거리를 구하여라¶
In [6]:
target = df[['연령대코드','이동거리']].groupby('연령대코드').mean()
target
Out[6]:
| 이동거리 | |
|---|---|
| 연령대코드 | |
| 20대 | 3211.890552 |
| 30대 | 3341.443859 |
| 40대 | 3514.857416 |
| 50대 | 3593.668100 |
| 60대 | 3538.145737 |
| 70대~ | 3085.039641 |
| ~10대 | 2634.426279 |
36. 연령대 코드가 20대인 데이터를 추출하고,이동거리값이 추출한 데이터의 이동거리값의 평균 이상인 데이터를 추출한다.최종 추출된 데이터를 대여일자, 대여소 번호 순서로 내림차순 정렬 후 1행부터 200행까지의 탄소량의 평균을 소숫점 3째 자리까지 구하여라¶
In [43]:
target = df.loc[df['연령대코드']== '20대']
target = target.loc[target['이동거리'] >= target['이동거리'].mean()]
target.sort_values(by=['대여일자','대여소번호'], ascending=False, inplace=True)
target = target.iloc[0:200]
target['탄소량'] = target['탄소량'].astype('float')
print(round(target['탄소량'].mean(),3))
1.613
In [50]:
target = df.loc[(df['대여일자']=='2021-06-07') & (df['연령대코드']=='~10대')]
print(target['이용건수'].median())
1.0
38. 평일 (월~금) 출근 시간대(오전 6,7,8시)의 대여소별 이용 횟수를 구해서 데이터 프레임 형태로 표현한 후 각 대여시간별 이용 횟수의 상위 3개 대여소와 이용횟수를 출력하라¶
In [92]:
target = df.loc[(df['day_name'].isin(['Monday','Tuesday','Wednesday','Thursday','Friday'])) & (df['대여시간'].isin([6,7,8]))]
target = target.groupby(['대여시간','대여소번호']).size().to_frame('이용횟수')
target = target.sort_values(['대여시간','이용횟수'], ascending=False).groupby('대여시간').head(3)
target
Out[92]:
| 이용횟수 | ||
|---|---|---|
| 대여시간 | 대여소번호 | |
| 8 | 2701 | 119 |
| 646 | 115 | |
| 1152 | 92 | |
| 7 | 259 | 104 |
| 230 | 77 | |
| 726 | 77 | |
| 6 | 2744 | 45 |
| 1125 | 40 | |
| 1028 | 36 |
39. 이동거리의 평균 이상의 이동거리 값을 가지는 데이터를 추출하여 추출데이터의 이동거리의 표본표준편차 값을 구하여라¶
In [101]:
target = df.loc[df['이동거리'] >= df['이동거리'].mean()]
print(target['이동거리'].std())
5092.139707505305
40. 남성(‘M’ or ‘m’)과 여성(‘F’ or ‘f’)의 이동거리값의 평균값을 구하여라¶
In [124]:
df['sex'] = df['성별'].map(lambda x : '남' if ((x=='M') | (x=='m')) else '여')
target = df[['sex','이동거리']].groupby('sex').mean()
target
Out[124]:
| 이동거리 | |
|---|---|
| sex | |
| 남 | 3209.110871 |
| 여 | 3468.575025 |
41. 데이터는 2018년도와 2019년도의 전세계 행복 지수를 표현한다. 각년도의 행복랭킹 10위를 차지한 나라의 행복점수의 평균을 구하여라¶
In [220]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/happy2/happiness.csv', encoding='utf')
df
Out[220]:
| 행복랭킹 | 나라명 | 점수 | 상대GDP | 사회적지원 | 행복기대치 | 선택의 자유도 | 관대함 | 부패에 대한인식 | 년도 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Finland | 7.769 | 1.340 | 1.587 | 0.986 | 0.596 | 0.153 | 0.393 | 2019 |
| 1 | 2 | Denmark | 7.600 | 1.383 | 1.573 | 0.996 | 0.592 | 0.252 | 0.410 | 2019 |
| 2 | 3 | Norway | 7.554 | 1.488 | 1.582 | 1.028 | 0.603 | 0.271 | 0.341 | 2019 |
| 3 | 4 | Iceland | 7.494 | 1.380 | 1.624 | 1.026 | 0.591 | 0.354 | 0.118 | 2019 |
| 4 | 5 | Netherlands | 7.488 | 1.396 | 1.522 | 0.999 | 0.557 | 0.322 | 0.298 | 2019 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 307 | 152 | Yemen | 3.355 | 0.442 | 1.073 | 0.343 | 0.244 | 0.083 | 0.064 | 2018 |
| 308 | 153 | Tanzania | 3.303 | 0.455 | 0.991 | 0.381 | 0.481 | 0.270 | 0.097 | 2018 |
| 309 | 154 | South Sudan | 3.254 | 0.337 | 0.608 | 0.177 | 0.112 | 0.224 | 0.106 | 2018 |
| 310 | 155 | Central African Republic | 3.083 | 0.024 | 0.000 | 0.010 | 0.305 | 0.218 | 0.038 | 2018 |
| 311 | 156 | Burundi | 2.905 | 0.091 | 0.627 | 0.145 | 0.065 | 0.149 | 0.076 | 2018 |
312 rows × 10 columns
In [221]:
target = df.loc[df['행복랭킹']==10]
print(target['점수'].mean())
7.259
42. 데이터는 2018년도와 2019년도의 전세계 행복 지수를 표현한다. 각년도의 행복랭킹 50위이내의 나라들의 각각의 행복점수 평균을 데이터프레임으로 표시하라¶
In [222]:
target = df.loc[df['행복랭킹']<=50]
target = target[['년도','점수']].groupby('년도').mean()
target
Out[222]:
| 점수 | |
|---|---|
| 년도 | |
| 2018 | 6.64678 |
| 2019 | 6.67002 |
43. 2018년도 데이터들만 추출하여 행복점수와 부패에 대한 인식에 대한 상관계수를 구하여라¶
In [223]:
target = df.loc[df['년도']==2018][['점수','부패에 대한인식']].corr()
print(target.iloc[0,1])
0.40529152271510027
44. 2018년도와 2019년도의 행복랭킹이 변화하지 않은 나라명의 수를 구하여라¶
In [224]:
target = len(df[['행복랭킹','나라명']])-len(df[['행복랭킹','나라명']].drop_duplicates())
target
Out[224]:
15
45. 2019년도 데이터들만 추출하여 각변수간 상관계수를 구하고 내림차순으로 정렬한 후 상위 5개를 데이터 프레임으로 출력하라. 컬럼명은 v1,v2,corr으로 표시하라¶
In [225]:
target = df.loc[df['년도']==2019].corr().unstack().to_frame().reset_index().dropna()
target = target.loc[target[0]!=1].sort_values(by=0, ascending=False).drop_duplicates(0)
target.columns = ['v1','v2','corr']
target.head(5)
Out[225]:
| v1 | v2 | corr | |
|---|---|---|---|
| 38 | 행복기대치 | 상대GDP | 0.835462 |
| 19 | 상대GDP | 점수 | 0.793883 |
| 37 | 행복기대치 | 점수 | 0.779883 |
| 28 | 사회적지원 | 점수 | 0.777058 |
| 29 | 사회적지원 | 상대GDP | 0.754906 |
46. 각 년도별 하위 행복점수의 하위 5개 국가의 평균 행복점수를 구하여라¶
In [226]:
target = df[['년도','점수']].sort_values(by=['년도','점수'], ascending = True).groupby('년도').head(5)
target = target.groupby('년도').mean()
target
Out[226]:
| 점수 | |
|---|---|
| 년도 | |
| 2018 | 3.1800 |
| 2019 | 3.1408 |
47. 2019년 데이터를 추출하고 해당데이터의 상대 GDP 평균 이상의 나라들과 평균 이하의 나라들의 행복점수 평균을 각각 구하고 그 차이값을 출력하라¶
In [227]:
target = df.loc[df['년도']==2019]
target
avg_up = target.loc[target['상대GDP']>=target['상대GDP'].mean()]
avg_down = target.loc[target['상대GDP']<=target['상대GDP'].mean()]
avg_up_score = avg_up['점수'].mean()
avg_down_score = avg_down['점수'].mean()
print(avg_up_score)
print(avg_down_score)
print(avg_up_score-avg_down_score)
6.013204545454547 4.6227205882352935 1.3904839572192538
48. 각년도의 부패에 대한인식을 내림차순 정렬했을때 상위 20개 국가의 부패에 대한인식의 평균을 구하여라¶
In [233]:
target = df[['년도','부패에 대한인식']].sort_values(by=['년도','부패에 대한인식'], ascending=False).groupby('년도').head(20)
target = target.groupby('년도').mean()
target
Out[233]:
| 부패에 대한인식 | |
|---|---|
| 년도 | |
| 2018 | 0.3267 |
| 2019 | 0.3201 |
In [229]:
df
Out[229]:
| 행복랭킹 | 나라명 | 점수 | 상대GDP | 사회적지원 | 행복기대치 | 선택의 자유도 | 관대함 | 부패에 대한인식 | 년도 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Finland | 7.769 | 1.340 | 1.587 | 0.986 | 0.596 | 0.153 | 0.393 | 2019 |
| 1 | 2 | Denmark | 7.600 | 1.383 | 1.573 | 0.996 | 0.592 | 0.252 | 0.410 | 2019 |
| 2 | 3 | Norway | 7.554 | 1.488 | 1.582 | 1.028 | 0.603 | 0.271 | 0.341 | 2019 |
| 3 | 4 | Iceland | 7.494 | 1.380 | 1.624 | 1.026 | 0.591 | 0.354 | 0.118 | 2019 |
| 4 | 5 | Netherlands | 7.488 | 1.396 | 1.522 | 0.999 | 0.557 | 0.322 | 0.298 | 2019 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 307 | 152 | Yemen | 3.355 | 0.442 | 1.073 | 0.343 | 0.244 | 0.083 | 0.064 | 2018 |
| 308 | 153 | Tanzania | 3.303 | 0.455 | 0.991 | 0.381 | 0.481 | 0.270 | 0.097 | 2018 |
| 309 | 154 | South Sudan | 3.254 | 0.337 | 0.608 | 0.177 | 0.112 | 0.224 | 0.106 | 2018 |
| 310 | 155 | Central African Republic | 3.083 | 0.024 | 0.000 | 0.010 | 0.305 | 0.218 | 0.038 | 2018 |
| 311 | 156 | Burundi | 2.905 | 0.091 | 0.627 | 0.145 | 0.065 | 0.149 | 0.076 | 2018 |
312 rows × 10 columns
49. 2018년도 행복랭킹 50위 이내에 포함됐다가 2019년 50위 밖으로 밀려난 국가의 숫자를 구하여라¶
In [261]:
target_2018 = set(df.loc[(df['년도']==2018)&(df['행복랭킹']<=50)]['나라명'])
target_2019 = set(df.loc[(df['년도']==2019)&(df['행복랭킹']<=50)]['나라명'])
target = target_2018 - target_2019
print(len(target))
4
50. 2018년,2019년 모두 기록이 있는 나라들 중 년도별 행복점수가 가장 증가한 나라와 그 증가 수치는?¶
In [403]:
target = df['나라명'].value_counts()
list = target.loc[target==2].index
target = df.loc[df['나라명'].isin(list)]
target_18 = target.loc[target['년도']==2018][['나라명','점수']]
target_19 = target.loc[target['년도']==2019][['나라명','점수']]
target_18['점수'] = target_18['점수'].map(lambda x: -x)
#display(target_18)
#display(target_19)
target = pd.merge(target_19, target_18, on='나라명')
target['점수'] = target['점수_x'] + target['점수_y']
target.sort_values(by='점수', ascending = False, inplace=True)
print(target.loc[140,['나라명','점수']])
나라명 Burundi 점수 0.87 Name: 140, dtype: object
51. DateTime컬럼을 통해 각 월별로 몇개의 데이터가 있는지 데이터 프레임으로 구하여라¶
In [492]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/consum/Tetuan%20City%20power%20consumption.csv')
df['DateTime'] = pd.to_datetime(df['DateTime'])
target = df.groupby(df['DateTime'].dt.month).size().to_frame('count')
target
Out[492]:
| count | |
|---|---|
| DateTime | |
| 1 | 4464 |
| 2 | 4032 |
| 3 | 4464 |
| 4 | 4320 |
| 5 | 4464 |
| 6 | 4320 |
| 7 | 4464 |
| 8 | 4464 |
| 9 | 4320 |
| 10 | 4464 |
| 11 | 4320 |
| 12 | 4320 |
52. 3월달의 각 시간대별 온도의 평균들 중 가장 낮은 시간대의 온도를 출력하라¶
In [493]:
target = df.loc[df['DateTime'].dt.month==3]
target = target.groupby(target['DateTime'].dt.hour).mean()
target = target.sort_values(by='Temperature', ascending=True)
print(target.loc[7,'Temperature'])
11.506612903225806
53. 3월달의 각 시간대별 온도의 평균들 중 가장 높은 시간대의 온도를 출력하라¶
In [494]:
target = df.loc[df['DateTime'].dt.month==3]
target = target.groupby(target['DateTime'].dt.hour).mean()
target = target.sort_values(by='Temperature', ascending=False)
print(target.loc[15,'Temperature'])
18.393602150537635
54. Zone 1 Power Consumption 컬럼의 value값의 크기가 Zone 2 Power Consumption 컬럼의 value값의 크기보다 큰 데이터들의 Humidity의 평균을 구하여라¶
In [495]:
target = df.loc[df['Zone 1 Power Consumption']>df['Zone 2 Power Consumption']]
print(target['Humidity'].mean())
68.23624448055094
55. 각 zone의 에너지 소비량의 상관관계를 구해서 데이터 프레임으로 표기하라¶
In [496]:
target = df[['Zone 1 Power Consumption','Zone 2 Power Consumption','Zone 3 Power Consumption']]
target.corr()
Out[496]:
| Zone 1 Power Consumption | Zone 2 Power Consumption | Zone 3 Power Consumption | |
|---|---|---|---|
| Zone 1 Power Consumption | 1.000000 | 0.834519 | 0.750733 |
| Zone 2 Power Consumption | 0.834519 | 1.000000 | 0.570932 |
| Zone 3 Power Consumption | 0.750733 | 0.570932 | 1.000000 |
56. Temperature의 값이 10미만의 경우 A, 10이상 20미만의 경우 B,20이상 30미만의 경우 C, 그 외의 경우 D라고 할때 각 단계의 데이터 숫자를 구하여라¶
In [497]:
target = df.copy()
target['Temperature'] = target['Temperature'].map(lambda x: 'A' if x < 10 else 'B' if 10 <= x < 20 else 'C' if 20 <= x < 30 else 'D')
target['Temperature'].value_counts()
Out[497]:
B 26993 C 21105 A 2874 D 1444 Name: Temperature, dtype: int64
57. 6월 데이터중 12시의 Temperature의 표준편차를 구하여라¶
In [500]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/consum/Tetuan%20City%20power%20consumption.csv')
df['DateTime'] = pd.to_datetime(df['DateTime'])
target = df.loc[(df['DateTime'].dt.month == 6) & (df['DateTime'].dt.hour == 12)]
print(target['Temperature'].std())
2.049941782795103
58. 6월 데이터중 12시의 Temperature의 분산을 구하여라¶
In [507]:
target = df.loc[(df['DateTime'].dt.month==6)&(df['DateTime'].dt.hour==12)]
print(target['Temperature'].var())
4.202261312849164
59. Temperature의 평균이상의 Temperature의 값을 가지는 데이터를 Temperature를 기준으로 정렬 했을때 4번째 행의 Humidity 값은?¶
In [512]:
target = df.loc[df['Temperature']>=df['Temperature'].mean()].sort_values(by='Temperature', ascending=True)
print(prtarget['Humidity'].values[3])
Out[512]:
87.9
60. Temperature의 중간값 이상의 Temperature의 값을 가지는 데이터를Temperature를 기준으로 정렬 했을때 4번째 행의 Humidity 값은?¶
In [516]:
target = df.loc[df['Temperature']>=df['Temperature'].median()].sort_values(by='Temperature', ascending=True)
print(target['Humidity'].values[3])
80.3
61. Legendary 컬럼은 전설포켓몬 유무를 나타낸다.전설포켓몬과 그렇지 않은 포켓몬들의 HP평균의 차이를 구하여라¶
In [12]:
#데이터 불러오기
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/pok/Pokemon.csv')
df
leg = df.loc[df['Legendary']==True]
no_leg = df.loc[df['Legendary']==False]
print(leg['HP'].mean() - no_leg['HP'].mean())
25.55614861329147
62. Type 1은 주속성 Type 2 는 부속성을 나타낸다. 가장 많은 부속성 종류는 무엇인가?¶
In [13]:
print(df['Type 2'].value_counts().index[0])
Flying
63. 가장 많은 Type 1 의 종의 평균 Attack 을 평균 Defense로 나눈값은?¶
In [14]:
df['Type 1'].value_counts()
target = df.loc[df['Type 1']=='Water']
print(target['Attack'].mean()/target['Defense'].mean())
1.0165238678090576
64. 포켓몬 세대(Generation) 중 가장많은 Legendary를 보유한 세대는 몇세대인가?¶
In [15]:
target = df.loc[df['Legendary']==True].Generation.value_counts().index[0]
target
Out[15]:
3
65. ‘HP’, ‘Attack’, ‘Defense’, ‘Sp. Atk’, ‘Sp. Def’, ‘Speed’ 간의 상관 계수중 가장 절댓값이 큰 두 변수와 그 값을 구하여라¶
In [16]:
target = df[['HP','Attack','Defense','Sp. Atk','Sp. Def','Speed']].corr().unstack().reset_index(drop=False).rename(columns={0:'corr'})
target = target.loc[target['corr']!=1].sort_values(by='corr', ascending=False).drop_duplicates('corr', keep='first')
target.iloc[0,:]
Out[16]:
level_0 Sp. Def level_1 Defense corr 0.510747 Name: 26, dtype: object
66. 각 Generation의 Attack으로 오름차순 정렬시 상위 3개 데이터들(18개)의 Attack의 전체 평균을 구하여라¶
In [17]:
target = df.sort_values(by=['Generation','Attack'])
target = target[['Generation','Attack']].groupby('Generation').head(3)
target['Attack'].mean()
Out[17]:
19.5
67. 각 Generation의 Attack으로 내림차순 정렬시 상위 5개 데이터들(30개)의 Attack의 전체 평균을 구하여라¶
In [18]:
target = df[['Generation','Attack']].sort_values(by=['Generation','Attack'], ascending=False)
target = target.groupby('Generation').head(5)
print(target['Attack'].mean())
157.23333333333332
68. 가장 흔하게 발견되는 (Type1 , Type2) 의 쌍은 무엇인가?¶
In [19]:
target = df[['Type 1','Type 2']].value_counts().to_frame('count').reset_index(drop=False)
print(target.iloc[0,:])
target
Type 1 Normal Type 2 Flying count 24 Name: 0, dtype: object
Out[19]:
| Type 1 | Type 2 | count | |
|---|---|---|---|
| 0 | Normal | Flying | 24 |
| 1 | Grass | Poison | 15 |
| 2 | Bug | Flying | 14 |
| 3 | Bug | Poison | 12 |
| 4 | Ghost | Grass | 10 |
| ... | ... | ... | ... |
| 131 | Fire | Rock | 1 |
| 132 | Ice | Ghost | 1 |
| 133 | Fire | Dragon | 1 |
| 134 | Fighting | Flying | 1 |
| 135 | Water | Steel | 1 |
136 rows × 3 columns
69. 한번씩만 존재하는 (Type1 , Type2)의 쌍의 갯수는 몇개인가?¶
In [20]:
target = df[['Type 1','Type 2']].value_counts().to_frame('count').reset_index(drop=False)
target = target.loc[target['count']==1]
print(len(target))
39
70. 한번씩만 존재하는 (Type1 , Type2)의 쌍을 각 세대(Generation)은 각각 몇개씩 가지고 있는가?¶
In [21]:
target = df[['Type 1','Type 2']].value_counts().to_frame('count').reset_index(drop=False)
target = target.loc[target['count']==1]
target
a = target[['Type 1','Type 2']].values
list = []
for i in a:
sp = df.loc[(df['Type 1']==i[0]) & (df['Type 2']==i[1])]
list.append(sp)
#print(list)
target_df = pd.concat(list).drop(columns='#')
target_df['Generation'].value_counts().sort_index()
Out[21]:
1 1 2 4 3 5 4 13 5 7 6 9 Name: Generation, dtype: int64
71. 전체데이터의 수축기혈압(최고) - 이완기혈압(최저)의 평균을 구하여라¶
In [26]:
import pandas as pd
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/body/body.csv')
display(df)
target = (df['수축기혈압(최고) : mmHg'] - df['이완기혈압(최저) : mmHg']).mean()
target
| 측정나이 | 측정회원성별 | 신장 : cm | 체중 : kg | 체지방율 : % | 이완기혈압(최저) : mmHg | 수축기혈압(최고) : mmHg | 악력D : kg | 앉아윗몸앞으로굽히기 : cm | 교차윗몸일으키기 : 회 | 제자리 멀리뛰기 : cm | 등급 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 59.0 | M | 175.0 | 70.6 | 19.2 | 91.0 | 150.0 | 40.6 | 12.2 | 30.0 | 179.0 | C |
| 1 | 40.0 | F | 161.4 | 45.8 | 21.7 | 62.0 | 119.0 | 22.1 | 16.0 | 32.0 | 165.0 | B |
| 2 | 27.0 | M | 176.6 | 84.8 | 19.2 | 87.0 | 153.0 | 45.9 | 13.2 | 61.0 | 216.0 | B |
| 3 | 38.0 | M | 167.6 | 76.7 | 24.7 | 63.0 | 132.0 | 43.6 | 16.0 | 45.0 | 231.0 | A |
| 4 | 21.0 | M | 165.2 | 66.2 | 21.5 | 83.0 | 106.0 | 33.5 | 10.6 | 46.0 | 198.0 | C |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 13391 | 61.0 | M | 167.0 | 65.8 | 22.2 | 71.0 | 130.0 | 33.7 | 14.5 | 37.0 | 182.0 | C |
| 13392 | 25.0 | M | 170.7 | 64.2 | 22.4 | 57.0 | 121.0 | 32.5 | 11.8 | 48.0 | 196.0 | C |
| 13393 | 47.0 | M | 166.2 | 77.5 | 22.8 | 84.0 | 133.0 | 52.4 | 11.9 | 45.0 | 220.0 | B |
| 13394 | 29.0 | M | 175.4 | 74.4 | 16.1 | 77.0 | 124.0 | 58.4 | 23.5 | 48.0 | 245.0 | B |
| 13395 | 28.0 | M | 173.8 | 78.5 | 17.3 | 88.0 | 119.0 | 50.1 | 19.9 | 57.0 | 237.0 | A |
13396 rows × 12 columns
Out[26]:
52.19539414750672
72. 50~59세의 신장평균을 구하여라¶
In [23]:
target = df.loc[(df['측정나이']>=50) & (df['측정나이']<=59)]
target['신장 : cm'].mean()
Out[23]:
164.07490107405295
In [24]:
df
Out[24]:
| 측정나이 | 측정회원성별 | 신장 : cm | 체중 : kg | 체지방율 : % | 이완기혈압(최저) : mmHg | 수축기혈압(최고) : mmHg | 악력D : kg | 앉아윗몸앞으로굽히기 : cm | 교차윗몸일으키기 : 회 | 제자리 멀리뛰기 : cm | 등급 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 59.0 | M | 175.0 | 70.6 | 19.2 | 91.0 | 150.0 | 40.6 | 12.2 | 30.0 | 179.0 | C |
| 1 | 40.0 | F | 161.4 | 45.8 | 21.7 | 62.0 | 119.0 | 22.1 | 16.0 | 32.0 | 165.0 | B |
| 2 | 27.0 | M | 176.6 | 84.8 | 19.2 | 87.0 | 153.0 | 45.9 | 13.2 | 61.0 | 216.0 | B |
| 3 | 38.0 | M | 167.6 | 76.7 | 24.7 | 63.0 | 132.0 | 43.6 | 16.0 | 45.0 | 231.0 | A |
| 4 | 21.0 | M | 165.2 | 66.2 | 21.5 | 83.0 | 106.0 | 33.5 | 10.6 | 46.0 | 198.0 | C |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 13391 | 61.0 | M | 167.0 | 65.8 | 22.2 | 71.0 | 130.0 | 33.7 | 14.5 | 37.0 | 182.0 | C |
| 13392 | 25.0 | M | 170.7 | 64.2 | 22.4 | 57.0 | 121.0 | 32.5 | 11.8 | 48.0 | 196.0 | C |
| 13393 | 47.0 | M | 166.2 | 77.5 | 22.8 | 84.0 | 133.0 | 52.4 | 11.9 | 45.0 | 220.0 | B |
| 13394 | 29.0 | M | 175.4 | 74.4 | 16.1 | 77.0 | 124.0 | 58.4 | 23.5 | 48.0 | 245.0 | B |
| 13395 | 28.0 | M | 173.8 | 78.5 | 17.3 | 88.0 | 119.0 | 50.1 | 19.9 | 57.0 | 237.0 | A |
13396 rows × 12 columns
73. 연령대 (20~29 : 20대 …) 별 인원수를 구하여라¶
In [35]:
def solution(x):
if 20<=x<=29:
return '20대'
elif 30<=x<=39:
return '30대'
elif 40<=x<=49:
return '40대'
elif 50<=x<=59:
return '50대'
else:
return '60대'
df['연령대'] = df['측정나이'].apply(solution)
target = df['연령대'].value_counts()
target
Out[35]:
20대 5831 30대 2660 40대 1801 50대 1769 60대 1335 Name: 연령대, dtype: int64
74. 연령대 (20~29 : 20대 …) 별 등급의 숫자를 데이터 프레임으로 표현하라¶
In [41]:
target = df.groupby(['연령대','등급']).size().to_frame('count').reset_index(drop=False)
target
Out[41]:
| 연령대 | 등급 | count | |
|---|---|---|---|
| 0 | 20대 | A | 1585 |
| 1 | 20대 | B | 1443 |
| 2 | 20대 | C | 1455 |
| 3 | 20대 | D | 1348 |
| 4 | 30대 | A | 743 |
| 5 | 30대 | B | 697 |
| 6 | 30대 | C | 626 |
| 7 | 30대 | D | 594 |
| 8 | 40대 | A | 386 |
| 9 | 40대 | B | 428 |
| 10 | 40대 | C | 455 |
| 11 | 40대 | D | 532 |
| 12 | 50대 | A | 321 |
| 13 | 50대 | B | 410 |
| 14 | 50대 | C | 474 |
| 15 | 50대 | D | 564 |
| 16 | 60대 | A | 314 |
| 17 | 60대 | B | 371 |
| 18 | 60대 | C | 339 |
| 19 | 60대 | D | 311 |
75. 남성 중 A등급과 D등급의 체지방률 평균의 차이(큰 값에서 작은 값의 차)를 구하여라¶
In [52]:
target_A = df.loc[(df['측정회원성별']=='M') & (df['등급']=='A')]
display(target_A.head())
target_D = df.loc[(df['측정회원성별']=='M') & (df['등급']=='D')]
display(target_D.head())
print(target_D['체지방율 : %'].mean() - target_A['체지방율 : %'].mean())
| 측정나이 | 측정회원성별 | 신장 : cm | 체중 : kg | 체지방율 : % | 이완기혈압(최저) : mmHg | 수축기혈압(최고) : mmHg | 악력D : kg | 앉아윗몸앞으로굽히기 : cm | 교차윗몸일으키기 : 회 | 제자리 멀리뛰기 : cm | 등급 | 연령대 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 3 | 38.0 | M | 167.6 | 76.70 | 24.7 | 63.0 | 132.0 | 43.6 | 16.0 | 45.0 | 231.0 | A | 30대 |
| 23 | 49.0 | M | 166.4 | 66.60 | 21.5 | 67.0 | 117.0 | 40.5 | 21.3 | 53.0 | 215.0 | A | 40대 |
| 30 | 28.0 | M | 167.8 | 65.18 | 19.0 | 82.0 | 140.0 | 47.6 | 20.6 | 67.0 | 235.0 | A | 20대 |
| 32 | 29.0 | M | 182.4 | 91.30 | 19.9 | 91.0 | 159.0 | 60.0 | 25.5 | 51.0 | 215.0 | A | 20대 |
| 45 | 26.0 | M | 169.4 | 68.50 | 12.7 | 85.0 | 128.0 | 45.7 | 20.0 | 63.0 | 250.0 | A | 20대 |
| 측정나이 | 측정회원성별 | 신장 : cm | 체중 : kg | 체지방율 : % | 이완기혈압(최저) : mmHg | 수축기혈압(최고) : mmHg | 악력D : kg | 앉아윗몸앞으로굽히기 : cm | 교차윗몸일으키기 : 회 | 제자리 멀리뛰기 : cm | 등급 | 연령대 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 7 | 33.0 | M | 173.4 | 76.90 | 25.5 | 74.0 | 116.0 | 45.6 | 6.0 | 33.0 | 226.0 | D | 30대 |
| 10 | 39.0 | M | 171.0 | 80.20 | 27.9 | 83.0 | 120.0 | 38.9 | 4.2 | 44.0 | 183.0 | D | 30대 |
| 11 | 60.0 | M | 166.4 | 70.80 | 25.6 | 92.0 | 154.0 | 35.6 | 11.7 | 38.0 | 193.0 | D | 60대 |
| 12 | 21.0 | M | 172.9 | 72.50 | 21.7 | 66.0 | 128.0 | 47.9 | 7.9 | 41.0 | 208.0 | D | 20대 |
| 13 | 27.0 | M | 181.4 | 88.74 | 26.1 | 75.0 | 131.0 | 40.9 | 11.0 | 56.0 | 195.0 | D | 20대 |
7.932086486137457
76. 여성 중 A등급과 D등급의 체중의 평균의 차이(큰 값에서 작은 값의 차)를 구하여라¶
In [59]:
target_A = df.loc[(df['측정회원성별']=='F') & (df['등급']=='A')]
target_D = df.loc[(df['측정회원성별']=='F') & (df['등급']=='D')]
print(target_D['체중 : kg'].mean() - target_A['체중 : kg'].mean())
5.176211590296511
77. bmi는 자신의 몸무게(kg)를 키의 제곱(m)으로 나눈값이다. 데이터의 bmi 를 구한 새로운 컬럼을 만들고 남성의 bmi 평균을 구하여라¶
In [68]:
df['bmi'] = df['체중 : kg'] / (df['신장 : cm']/100)**2
target = df.loc[df['측정회원성별']=='M']
target['bmi'].mean()
Out[68]:
24.461344098193027
78. bmi보다 체지방율이 높은 사람들의 체중평균을 구하여라¶
In [71]:
target = df.loc[df['bmi']<df['체지방율 : %']]
target['체중 : kg'].mean()
Out[71]:
61.740880639254314
79. 남성과 여성의 악력 평균의 차이를 구하여라¶
In [74]:
target_m = df.loc[df['측정회원성별']=='M']['악력D : kg'].mean()
target_f = df.loc[df['측정회원성별']=='F']['악력D : kg'].mean()
print(target_m - target_f)
17.559541850474677
80. 남성과 여성의 교차윗몸일으키기 횟수의 평균의 차이를 구하여라¶
In [77]:
target_M = df.loc[df['측정회원성별']=='M']['교차윗몸일으키기 : 회'].mean()
target_F = df.loc[df['측정회원성별']=='F']['교차윗몸일으키기 : 회'].mean()
print(target_M-target_F)
14.243156833157634
In [69]:
df
Out[69]:
| 측정나이 | 측정회원성별 | 신장 : cm | 체중 : kg | 체지방율 : % | 이완기혈압(최저) : mmHg | 수축기혈압(최고) : mmHg | 악력D : kg | 앉아윗몸앞으로굽히기 : cm | 교차윗몸일으키기 : 회 | 제자리 멀리뛰기 : cm | 등급 | 연령대 | bmi | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 59.0 | M | 175.0 | 70.6 | 19.2 | 91.0 | 150.0 | 40.6 | 12.2 | 30.0 | 179.0 | C | 50대 | 23.053061 |
| 1 | 40.0 | F | 161.4 | 45.8 | 21.7 | 62.0 | 119.0 | 22.1 | 16.0 | 32.0 | 165.0 | B | 40대 | 17.581601 |
| 2 | 27.0 | M | 176.6 | 84.8 | 19.2 | 87.0 | 153.0 | 45.9 | 13.2 | 61.0 | 216.0 | B | 20대 | 27.190328 |
| 3 | 38.0 | M | 167.6 | 76.7 | 24.7 | 63.0 | 132.0 | 43.6 | 16.0 | 45.0 | 231.0 | A | 30대 | 27.305324 |
| 4 | 21.0 | M | 165.2 | 66.2 | 21.5 | 83.0 | 106.0 | 33.5 | 10.6 | 46.0 | 198.0 | C | 20대 | 24.257046 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 13391 | 61.0 | M | 167.0 | 65.8 | 22.2 | 71.0 | 130.0 | 33.7 | 14.5 | 37.0 | 182.0 | C | 60대 | 23.593531 |
| 13392 | 25.0 | M | 170.7 | 64.2 | 22.4 | 57.0 | 121.0 | 32.5 | 11.8 | 48.0 | 196.0 | C | 20대 | 22.032713 |
| 13393 | 47.0 | M | 166.2 | 77.5 | 22.8 | 84.0 | 133.0 | 52.4 | 11.9 | 45.0 | 220.0 | B | 40대 | 28.056899 |
| 13394 | 29.0 | M | 175.4 | 74.4 | 16.1 | 77.0 | 124.0 | 58.4 | 23.5 | 48.0 | 245.0 | B | 20대 | 24.183199 |
| 13395 | 28.0 | M | 173.8 | 78.5 | 17.3 | 88.0 | 119.0 | 50.1 | 19.9 | 57.0 | 237.0 | A | 20대 | 25.987836 |
13396 rows × 14 columns
81. 여름철(6월,7월,8월) 이화동이 수영동보다 높은 기온을 가진 시간대는 몇개인가?¶
In [89]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/weather/weather2.csv')
display(df)
df['time'] = pd.to_datetime(df['time'])
target = df.loc[(df['time'].dt.month.isin([6,7,8])) & (df['이화동기온'] > df['수영동기온'])]
print(len(target['time']))
| time | 이화동강수 | 이화동기온 | 수영동강수 | 수영동기온 | |
|---|---|---|---|---|---|
| 0 | 2020-01-01 00:00:00 | 0.1 | -3.9 | 0.0 | 2.5 |
| 1 | 2020-01-01 01:00:00 | 0.0 | -3.1 | 0.0 | 3.4 |
| 2 | 2020-01-01 02:00:00 | 0.0 | -1.8 | 0.0 | 3.8 |
| 3 | 2020-01-01 03:00:00 | 0.0 | -0.8 | 0.0 | 4.6 |
| 4 | 2020-01-01 04:00:00 | 0.0 | -0.1 | 0.0 | 5.1 |
| ... | ... | ... | ... | ... | ... |
| 8779 | 2020-12-31 19:00:00 | 0.0 | -9.5 | 0.0 | -4.5 |
| 8780 | 2020-12-31 20:00:00 | 0.0 | -9.5 | 0.0 | -5.0 |
| 8781 | 2020-12-31 21:00:00 | 0.0 | -9.3 | 0.0 | -6.5 |
| 8782 | 2020-12-31 22:00:00 | 0.0 | -9.2 | 0.0 | -4.6 |
| 8783 | 2020-12-31 23:00:00 | 0.0 | -7.8 | 0.0 | -0.2 |
8784 rows × 5 columns
1415
82. 이화동과 수영동의 최대강수량의 시간대를 각각 구하여라¶
In [98]:
target_e_max = df.loc[df['이화동강수'] == df['이화동강수'].max()]
#target_e_max
target_s_max = df.loc[df['수영동강수'] == df['수영동강수'].max()]
#target_s_max
print(target_e_max['time'].values, target_s_max['time'].values)
['2020-09-30T09:00:00.000000000'] ['2020-07-23T12:00:00.000000000']
83. 남성 이탈(Exited)이 가장 많은 국가(Geography)는 어디이고 이탈 인원은 몇명인가?¶
In [22]:
import pandas as pd
#서비스 이탈 예측 데이터
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/train.csv')
display(df.head())
target = df.loc[(df['Exited'] == 1) & (df['Gender']=='Male')]['Geography'].value_counts()
target.head(1)
| RowNumber | CustomerId | Surname | CreditScore | Geography | Gender | Age | Tenure | Balance | NumOfProducts | HasCrCard | IsActiveMember | EstimatedSalary | Exited | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 6842 | 15793491 | Cherkasova | 714 | Germany | Male | 26 | 3 | 119545.48 | 2 | 1 | 0 | 65482.94 | 0 |
| 1 | 8963 | 15607874 | Keane | 687 | France | Male | 38 | 0 | 144450.58 | 1 | 0 | 1 | 137276.83 | 0 |
| 2 | 7047 | 15737627 | Rivero | 589 | Germany | Female | 20 | 2 | 121093.29 | 2 | 1 | 0 | 3529.72 | 0 |
| 3 | 7503 | 15697844 | Whitehouse | 721 | Spain | Female | 32 | 10 | 0.00 | 1 | 1 | 0 | 136119.96 | 1 |
| 4 | 3439 | 15722404 | Carpenter | 445 | France | Female | 30 | 3 | 0.00 | 2 | 1 | 1 | 127939.19 | 0 |
Out[22]:
Germany 287 Name: Geography, dtype: int64
84. 카드를 소유(HasCrCard ==1)하고 있으면서 활성멤버(IsActiveMember ==1) 인 고객들의 평균 나이를 소숫점이하 4자리까지 구하여라?¶
In [23]:
target = df.loc[(df['HasCrCard'] == 1) & (df['IsActiveMember']==1)]['Age'].mean()
print(round(target,4))
39.6102
85. Balance 값이 중간값 이상을 가지는 고객들의 CreditScore의 표준편차를 소숫점이하 3자리까지 구하여라¶
In [24]:
target = df.loc[df['Balance']>= df['Balance'].median()]['CreditScore'].std()
print(round(target,3))
97.295
In [25]:
df.head()
Out[25]:
| RowNumber | CustomerId | Surname | CreditScore | Geography | Gender | Age | Tenure | Balance | NumOfProducts | HasCrCard | IsActiveMember | EstimatedSalary | Exited | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 6842 | 15793491 | Cherkasova | 714 | Germany | Male | 26 | 3 | 119545.48 | 2 | 1 | 0 | 65482.94 | 0 |
| 1 | 8963 | 15607874 | Keane | 687 | France | Male | 38 | 0 | 144450.58 | 1 | 0 | 1 | 137276.83 | 0 |
| 2 | 7047 | 15737627 | Rivero | 589 | Germany | Female | 20 | 2 | 121093.29 | 2 | 1 | 0 | 3529.72 | 0 |
| 3 | 7503 | 15697844 | Whitehouse | 721 | Spain | Female | 32 | 10 | 0.00 | 1 | 1 | 0 | 136119.96 | 1 |
| 4 | 3439 | 15722404 | Carpenter | 445 | France | Female | 30 | 3 | 0.00 | 2 | 1 | 1 | 127939.19 | 0 |
86. 수축기혈압과 이완기 혈압기 수치의 차이를 새로운 컬럼(‘혈압차’) 으로 생성하고, 연령대 코드별 각 그룹 중 ‘혈압차’ 의 분산이 5번째로 큰 연령대 코드를 구하여라¶
In [26]:
# 데이터 설명 : 2018년도 성인의 건강검 진데이터 (흡연상태 1- 흡연, 0-비흡연 )
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/smoke/train.csv')
df['혈압차'] = df['수축기혈압'] - df['이완기혈압']
target = df.groupby('연령대코드(5세단위)')['혈압차'].agg(['std']).sort_values(by='std', ascending=False)
print(target.index[4])
60
87. 비만도를 나타내는 지표인 WHtR는 허리둘레 / 키로 표현한다. 일반적으로 0.58이상이면 비만으로 분류한다. 데이터중 WHtR 지표상 비만인 인원의 남/여 비율을 구하여라¶
In [27]:
df['WHtR'] = df['허리둘레'] / df['신장(5Cm단위)']
target_m = df.loc[(df['성별코드']=='M') & (df['WHtR']>=0.58)]
target_f = df.loc[(df['성별코드']=='F') & (df['WHtR']>=0.58)]
print(len(target_m) / len(target_f))
1.1693877551020408
In [28]:
df.head()
Out[28]:
| 성별코드 | 연령대코드(5세단위) | 신장(5Cm단위) | 체중(5Kg단위) | 허리둘레 | 시력(좌) | 시력(우) | 청력(좌) | 청력(우) | 수축기혈압 | ... | 혈청크레아티닌 | (혈청지오티)AST | (혈청지오티)ALT | 감마지티피 | 흡연상태 | 구강검진수검여부 | 치아우식증유무 | 치석 | 혈압차 | WHtR | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | F | 55 | 145 | 55 | 73.0 | 0.7 | 0.5 | 1.0 | 1.0 | 129.0 | ... | 0.9 | 172.0 | 209.0 | 15.0 | 0 | Y | 0.0 | Y | 45.0 | 0.503448 |
| 1 | M | 40 | 180 | 55 | 74.0 | 1.5 | 1.5 | 1.0 | 1.0 | 102.0 | ... | 0.8 | 30.0 | 19.0 | 23.0 | 1 | Y | 0.0 | Y | 32.0 | 0.411111 |
| 2 | F | 55 | 150 | 50 | 72.0 | 1.0 | 0.2 | 1.0 | 1.0 | 116.0 | ... | 1.0 | 31.0 | 19.0 | 10.0 | 0 | Y | 0.0 | N | 44.0 | 0.480000 |
| 3 | M | 40 | 170 | 85 | 89.0 | 1.0 | 0.8 | 1.0 | 1.0 | 124.0 | ... | 1.0 | 26.0 | 38.0 | 108.0 | 1 | Y | 1.0 | Y | 44.0 | 0.523529 |
| 4 | F | 40 | 155 | 45 | 62.0 | 0.5 | 1.0 | 1.0 | 1.0 | 127.0 | ... | 0.7 | 20.0 | 11.0 | 13.0 | 0 | Y | 0.0 | N | 42.0 | 0.400000 |
5 rows × 28 columns
88. Vehicle_Age 값이 2년 이상인 사람들만 필터링 하고 그중에서 Annual_Premium 값이 전체 데이터의 중간값 이상인 사람들을 찾고, 그들의 Vintage값의 평균을 구하여라¶
In [40]:
#데이터 설명 : 자동차 보험 가입 예측
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/insurance/train.csv')
target = df.loc[(df['Vehicle_Age']=='> 2 Years') & (df['Annual_Premium']>=df['Annual_Premium'].median())]
print(target['Vintage'].mean())
154.43647182359118
89. vehicle_age에 따른 각 성별(gender)그룹의 Annual_Premium값의 평균을 구하여 아래 테이블과 동일하게 구현하라¶
In [46]:
target = df.groupby(['Vehicle_Age','Gender']).Annual_Premium.mean().unstack()
target
Out[46]:
| Gender | Female | Male |
|---|---|---|
| Vehicle_Age | ||
| 1-2 Year | 30762.245001 | 30413.088469 |
| < 1 Year | 29972.286702 | 30310.982212 |
| > 2 Years | 36108.366374 | 35303.870627 |
90. price_range 의 각 value를 그룹핑하여 각 그룹의 n_cores 의 빈도가 가장높은 value와 그 빈도수를 구하여라¶
In [62]:
#데이터 설명 : 핸드폰 가격예측 (price_range컬럼 0(저렴) ~3(매우비쌈) 범위 )
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/mobile/train.csv')
df.columns
target = df.groupby(['price_range','n_cores']).size().to_frame('count').reset_index(drop=False).sort_values(by=['price_range','count'], ascending=False)
target.groupby('price_range').head(1).sort_values(by='count', ascending=True)
Out[62]:
| price_range | n_cores | count | |
|---|---|---|---|
| 1 | 0 | 2 | 69 |
| 28 | 3 | 5 | 70 |
| 19 | 2 | 4 | 73 |
| 8 | 1 | 1 | 76 |
91. price_range 값이 3인 그룹에서 상관관계가 2번째로 높은 두 컬럼과 그 상관계수를 구하여라¶
In [86]:
target = df.loc[df['price_range']==3]
target = target.corr().unstack().to_frame('corr').dropna().reset_index(drop=False)
target = target.loc[target['corr'] != 1]
target['corr'] = abs(target['corr'])
target = target.sort_values(by='corr', ascending=False).reset_index(drop=True)
target.iloc[1,:]
Out[86]:
level_0 pc level_1 fc corr 0.635166 Name: 1, dtype: object
In [88]:
df.head()
Out[88]:
| battery_power | blue | clock_speed | dual_sim | fc | four_g | int_memory | m_dep | mobile_wt | n_cores | ... | px_height | px_width | ram | sc_h | sc_w | talk_time | three_g | touch_screen | wifi | price_range | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 842 | 0 | 2.2 | 0 | 1 | 0 | 7 | 0.6 | 188 | 2 | ... | 20 | 756 | 2549 | 9 | 7 | 19 | 0 | 0 | 1 | 1 |
| 1 | 1021 | 1 | 0.5 | 1 | 0 | 1 | 53 | 0.7 | 136 | 3 | ... | 905 | 1988 | 2631 | 17 | 3 | 7 | 1 | 1 | 0 | 2 |
| 2 | 563 | 1 | 0.5 | 1 | 2 | 1 | 41 | 0.9 | 145 | 5 | ... | 1263 | 1716 | 2603 | 11 | 2 | 9 | 1 | 1 | 0 | 2 |
| 3 | 615 | 1 | 2.5 | 0 | 0 | 0 | 10 | 0.8 | 131 | 6 | ... | 1216 | 1786 | 2769 | 16 | 8 | 11 | 1 | 0 | 0 | 2 |
| 4 | 1821 | 1 | 1.2 | 0 | 13 | 1 | 44 | 0.6 | 141 | 2 | ... | 1208 | 1212 | 1411 | 8 | 2 | 15 | 1 | 1 | 0 | 1 |
5 rows × 21 columns
92. Arrival Delay in Minutes 컬럼이 결측치인 데이터들 중 ‘neutral or dissatisfied’ 보다 ‘satisfied’의 수가 더 높은 Class는 어디 인가?¶
In [131]:
#데이터 설명 : 비행탑승 경험 만족도 (satisfaction 컬럼 : ‘neutral or dissatisfied’ or satisfied ) (83123, 24) shape
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/airline/train.csv')
df.head()
target = df.loc[df['Arrival Delay in Minutes'].isnull()].groupby(['Class','satisfaction']).size().to_frame('size').unstack()
target = target.loc[(target[('size','neutral or dissatisfied')]) < (target[('size','satisfied')])]
target
Out[131]:
| size | ||
|---|---|---|
| satisfaction | neutral or dissatisfied | satisfied |
| Class | ||
| Business | 36 | 76 |
93. ph값은 상당히 많은 결측치를 포함한다. 결측치를 제외한 나머지 데이터들 중 사분위값 기준 하위 25%의 값들의 평균값은?¶
In [146]:
#데이터 설명 : 수질 음용성 여부 (Potablillity 컬럼 : 0 ,1 )
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/waters/train.csv')
display(df.head())
target = df['ph'].dropna().loc[df['ph'] <= df['ph'].quantile(0.25)].mean()
target
| ph | Hardness | Solids | Chloramines | Sulfate | Conductivity | Organic_carbon | Trihalomethanes | Turbidity | Potability | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 7.918150 | 214.186611 | 23823.492888 | 7.290878 | 341.173322 | 411.424483 | 19.585002 | 25.057375 | 4.028958 | 0 |
| 1 | 5.422446 | 205.266080 | 18542.957451 | 5.491963 | 306.702227 | 382.080129 | 10.504023 | 67.493450 | 2.911751 | 1 |
| 2 | 7.341547 | 187.672402 | 21273.457066 | 7.784003 | NaN | 332.084293 | 16.842334 | 55.019151 | 4.025644 | 0 |
| 3 | 9.056245 | 197.666301 | 17403.532167 | 7.688917 | 337.460176 | 414.766631 | 15.349869 | 63.696746 | 3.319354 | 0 |
| 4 | 5.039374 | 142.860598 | 40829.353167 | 7.271543 | NaN | 386.803057 | 16.823773 | 52.297113 | 4.957420 | 0 |
Out[146]:
5.057093462441732
94. 흡연자와 비흡연자 각각 charges의 상위 10% 그룹의 평균의 차이는?¶
In [160]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/MedicalCost/train.csv')
display(df.head())
target_smoker = df.loc[df['smoker']=='yes']
target_nosmoker = df.loc[df['smoker']=='no']
target_smoker = target_smoker.loc[target_smoker['charges']>=target_smoker['charges'].quantile(0.90)]
target_nosmoker = target_nosmoker.loc[target_nosmoker['charges']>=target_nosmoker['charges'].quantile(0.90)]
print(target_smoker['charges'].mean()-target_nosmoker['charges'].mean())
| age | sex | bmi | children | smoker | region | charges | |
|---|---|---|---|---|---|---|---|
| 0 | 64 | female | 39.330 | 0 | no | northeast | 14901.51670 |
| 1 | 47 | female | 27.830 | 0 | yes | southeast | 23065.42070 |
| 2 | 52 | female | 33.300 | 2 | no | southwest | 10806.83900 |
| 3 | 33 | female | 22.135 | 1 | no | northeast | 5354.07465 |
| 4 | 30 | male | 31.400 | 1 | no | southwest | 3659.34600 |
29297.954548156158
95. bedrooms 의 빈도가 가장 높은 값을 가지는 데이터들의 price의 상위 10%와 하위 10%값의 차이를 구하여라¶
In [165]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/kingcountyprice//train.csv')
display(df.head())
target = df.loc[df['bedrooms']==df['bedrooms'].value_counts().index[0]]
print(target['price'].quantile(0.90) - target['price'].quantile(0.10))
| id | date | price | bedrooms | bathrooms | sqft_living | sqft_lot | floors | waterfront | view | ... | grade | sqft_above | sqft_basement | yr_built | yr_renovated | zipcode | lat | long | sqft_living15 | sqft_lot15 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 8961990160 | 20150413T000000 | 567500.0 | 3 | 2.5 | 2080 | 4556 | 2.0 | 0 | 0 | ... | 8 | 2080 | 0 | 1999 | 0 | 98074 | 47.6036 | -122.014 | 1530 | 5606 |
| 1 | 9455200205 | 20140604T000000 | 525000.0 | 3 | 2.0 | 1540 | 7800 | 1.0 | 0 | 0 | ... | 8 | 1540 | 0 | 2004 | 0 | 98125 | 47.7041 | -122.288 | 1510 | 7800 |
| 2 | 7853220670 | 20140918T000000 | 540000.0 | 3 | 2.5 | 2860 | 8935 | 2.0 | 0 | 0 | ... | 8 | 2860 | 0 | 2004 | 0 | 98065 | 47.5336 | -121.855 | 2650 | 6167 |
| 3 | 3298201170 | 20141110T000000 | 350000.0 | 3 | 1.0 | 940 | 7811 | 1.0 | 0 | 0 | ... | 6 | 940 | 0 | 1959 | 0 | 98008 | 47.6195 | -122.118 | 1180 | 7490 |
| 4 | 7972604355 | 20140521T000000 | 218000.0 | 3 | 1.0 | 1020 | 7874 | 1.0 | 0 | 0 | ... | 7 | 1020 | 0 | 1956 | 0 | 98106 | 47.5175 | -122.346 | 1290 | 7320 |
5 rows × 21 columns
505500.0
96. Serial No. 컬럼을 제외하고 ‘Chance of Admit’을 종속변수, 나머지 변수를 독립변수라 할때, 랜덤포레스트를 통해 회귀 예측을 할 떄 변수중요도 값을 출력하라 (시드값에 따라 순서는 달라질수 있음)¶
In [188]:
#데이터 설명 : 대학원 입학 가능성 예측
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/admission/train.csv')
df.drop(columns = 'Serial No.', inplace=True)
display(df)
from sklearn.ensemble import RandomForestRegressor
x = df.drop(columns = 'Chance of Admit')
y = df['Chance of Admit']
RFR = RandomForestRegressor()
RFR.fit(x,y)
print(RFR.feature_importances_)
print(x.columns)
result = pd.DataFrame({'importance' : RFR.feature_importances_} , x.columns).sort_values(by='importance', ascending=False)
result
| GRE Score | TOEFL Score | University Rating | SOP | LOR | CGPA | Research | Chance of Admit | |
|---|---|---|---|---|---|---|---|---|
| 0 | 328 | 110 | 4 | 4.0 | 2.5 | 9.02 | 1 | 0.81 |
| 1 | 323 | 113 | 3 | 4.0 | 4.0 | 8.88 | 1 | 0.79 |
| 2 | 296 | 95 | 2 | 3.0 | 2.0 | 7.54 | 1 | 0.44 |
| 3 | 334 | 116 | 4 | 4.0 | 3.0 | 8.00 | 1 | 0.78 |
| 4 | 321 | 114 | 5 | 4.5 | 4.5 | 9.16 | 1 | 0.87 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 395 | 329 | 114 | 5 | 4.0 | 5.0 | 9.30 | 1 | 0.86 |
| 396 | 307 | 109 | 3 | 4.0 | 3.0 | 8.00 | 1 | 0.62 |
| 397 | 298 | 98 | 2 | 1.5 | 2.5 | 7.50 | 1 | 0.44 |
| 398 | 339 | 116 | 4 | 4.0 | 3.5 | 9.80 | 1 | 0.96 |
| 399 | 326 | 114 | 4 | 4.0 | 3.5 | 9.16 | 1 | 0.86 |
400 rows × 8 columns
[0.08773013 0.02849618 0.01258504 0.02501658 0.02502868 0.81364906
0.00749434]
Index(['GRE Score', 'TOEFL Score', 'University Rating', 'SOP', 'LOR', 'CGPA',
'Research'],
dtype='object')
Out[188]:
| importance | |
|---|---|
| CGPA | 0.813649 |
| GRE Score | 0.087730 |
| TOEFL Score | 0.028496 |
| LOR | 0.025029 |
| SOP | 0.025017 |
| University Rating | 0.012585 |
| Research | 0.007494 |
97. quality 값이 3인 그룹과 8인 데이터그룹의 각 컬럼별 독립변수의 표준편차 값의 차이를 구할때 그값이 가장 큰 컬럼명을 구하여라¶
In [212]:
#데이터 설명 : 레드 와인 퀄리티 예측문제
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/Datamanim/datarepo/main/redwine/train.csv")
display(df)
target_q3 = df.loc[df['quality']==3].std().to_frame('std').reset_index(drop=False)
target_q8 = df.loc[df['quality']==8].std().to_frame('std').reset_index(drop=False)
display(target_q3)
display(target_q8)
result = pd.merge(target_q3, target_q8, on='index', how = 'inner')
result['std_chee'] = abs(result['std_x'] - result['std_y'])
print(result.loc[6,'index'])
result = result.sort_values(by='std_chee', ascending=False)
result
| fixed acidity | volatile acidity | citric acid | residual sugar | chlorides | free sulfur dioxide | total sulfur dioxide | density | pH | sulphates | alcohol | quality | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 5.0 | 0.38 | 0.01 | 1.6 | 0.048 | 26.0 | 60.0 | 0.99084 | 3.70 | 0.75 | 14.0 | 6 |
| 1 | 5.0 | 0.42 | 0.24 | 2.0 | 0.060 | 19.0 | 50.0 | 0.99170 | 3.72 | 0.74 | 14.0 | 8 |
| 2 | 7.1 | 0.36 | 0.30 | 1.6 | 0.080 | 35.0 | 70.0 | 0.99693 | 3.44 | 0.50 | 9.4 | 5 |
| 3 | 7.6 | 0.29 | 0.49 | 2.7 | 0.092 | 25.0 | 60.0 | 0.99710 | 3.31 | 0.61 | 10.1 | 6 |
| 4 | 7.7 | 0.51 | 0.28 | 2.1 | 0.087 | 23.0 | 54.0 | 0.99800 | 3.42 | 0.74 | 9.2 | 5 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 1274 | 8.8 | 0.61 | 0.14 | 2.4 | 0.067 | 10.0 | 42.0 | 0.99690 | 3.19 | 0.59 | 9.5 | 5 |
| 1275 | 8.0 | 0.59 | 0.16 | 1.8 | 0.065 | 3.0 | 16.0 | 0.99620 | 3.42 | 0.92 | 10.5 | 7 |
| 1276 | 10.0 | 0.35 | 0.45 | 2.5 | 0.092 | 20.0 | 88.0 | 0.99918 | 3.15 | 0.43 | 9.4 | 5 |
| 1277 | 8.0 | 1.18 | 0.21 | 1.9 | 0.083 | 14.0 | 41.0 | 0.99532 | 3.34 | 0.47 | 10.5 | 5 |
| 1278 | 8.6 | 0.47 | 0.30 | 3.0 | 0.076 | 30.0 | 135.0 | 0.99760 | 3.30 | 0.53 | 9.4 | 5 |
1279 rows × 12 columns
| index | std | |
|---|---|---|
| 0 | fixed acidity | 1.773493 |
| 1 | volatile acidity | 0.348273 |
| 2 | citric acid | 0.259845 |
| 3 | residual sugar | 1.453683 |
| 4 | chlorides | 0.068274 |
| 5 | free sulfur dioxide | 10.187138 |
| 6 | total sulfur dioxide | 17.190113 |
| 7 | density | 0.002052 |
| 8 | pH | 0.141902 |
| 9 | sulphates | 0.127475 |
| 10 | alcohol | 0.867628 |
| 11 | quality | 0.000000 |
| index | std | |
|---|---|---|
| 0 | fixed acidity | 1.789254 |
| 1 | volatile acidity | 0.145104 |
| 2 | citric acid | 0.180818 |
| 3 | residual sugar | 0.562478 |
| 4 | chlorides | 0.011750 |
| 5 | free sulfur dioxide | 11.669251 |
| 6 | total sulfur dioxide | 27.054090 |
| 7 | density | 0.002061 |
| 8 | pH | 0.191977 |
| 9 | sulphates | 0.123855 |
| 10 | alcohol | 1.141094 |
| 11 | quality | 0.000000 |
total sulfur dioxide
Out[212]:
| index | std_x | std_y | std_chee | |
|---|---|---|---|---|
| 6 | total sulfur dioxide | 17.190113 | 27.054090 | 9.863977 |
| 5 | free sulfur dioxide | 10.187138 | 11.669251 | 1.482114 |
| 3 | residual sugar | 1.453683 | 0.562478 | 0.891206 |
| 10 | alcohol | 0.867628 | 1.141094 | 0.273466 |
| 1 | volatile acidity | 0.348273 | 0.145104 | 0.203168 |
| 2 | citric acid | 0.259845 | 0.180818 | 0.079027 |
| 4 | chlorides | 0.068274 | 0.011750 | 0.056523 |
| 8 | pH | 0.141902 | 0.191977 | 0.050075 |
| 0 | fixed acidity | 1.773493 | 1.789254 | 0.015761 |
| 9 | sulphates | 0.127475 | 0.123855 | 0.003621 |
| 7 | density | 0.002052 | 0.002061 | 0.000009 |
| 11 | quality | 0.000000 | 0.000000 | 0.000000 |
98. 남성들의 연령대별 (10살씩 구분 0~9세 10~19세 …) Na_to_K값의 평균값을 구해서 데이터 프레임으로 표현하여라¶
In [225]:
#데이터 설명 : 투약하는 약을 분류
def solution(x):
if 10<=x<=19:
return '10대'
elif 20<=x<=29:
return '20대'
elif 30<=x<=39:
return '30대'
elif 40<=x<=49:
return '40대'
elif 50<=x<=59:
return '50대'
elif 60<=x<=69:
return '60대'
else:
return '70대'
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/drug/train.csv')
df['age_lange'] = df['Age'].apply(solution)
display(df)
target = df.loc[df['Sex']=='M'].groupby('age_lange').Na_to_K.mean().to_frame()
target
| Age | Sex | BP | Cholesterol | Na_to_K | Drug | age_lange | |
|---|---|---|---|---|---|---|---|
| 0 | 20 | F | NORMAL | NORMAL | 9.281 | 4 | 20대 |
| 1 | 24 | M | HIGH | NORMAL | 9.475 | 1 | 20대 |
| 2 | 34 | M | NORMAL | HIGH | 22.456 | 0 | 30대 |
| 3 | 17 | M | NORMAL | NORMAL | 10.832 | 4 | 10대 |
| 4 | 72 | M | LOW | HIGH | 16.310 | 0 | 70대 |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 152 | 58 | F | LOW | HIGH | 26.645 | 0 | 50대 |
| 153 | 30 | F | NORMAL | HIGH | 10.443 | 4 | 30대 |
| 154 | 20 | F | LOW | NORMAL | 11.686 | 4 | 20대 |
| 155 | 58 | M | HIGH | HIGH | 18.991 | 0 | 50대 |
| 156 | 16 | M | LOW | HIGH | 12.006 | 3 | 10대 |
157 rows × 7 columns
Out[225]:
| Na_to_K | |
|---|---|
| age_lange | |
| 10대 | 13.627000 |
| 20대 | 18.260769 |
| 30대 | 15.244143 |
| 40대 | 13.897273 |
| 50대 | 14.811273 |
| 60대 | 14.284308 |
| 70대 | 11.363857 |
99. 데이터의 Risk 값에 따른 score_a와 score_b의 평균값을 구하여라¶
In [231]:
# 데이터 설명 : 사기회사 분류
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/audit/train.csv')
display(df)
target = df[['Score_A','Score_B','Risk']].groupby('Risk').mean()
target
| Sector_score | LOCATION_ID | PARA_A | Score_A | Risk_A | PARA_B | Score_B | Risk_B | TOTAL | numbers | ... | RiSk_E | History | Prob | Risk_F | Score | Inherent_Risk | CONTROL_RISK | Detection_Risk | Audit_Risk | Risk | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2.72 | 14 | 4.53 | 0.6 | 2.718 | 87.93 | 0.6 | 52.758 | 92.46 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 4.0 | 108.362 | 0.4 | 0.5 | 21.6724 | 1 |
| 1 | 3.41 | 16 | 12.68 | 0.6 | 7.608 | 41.00 | 0.6 | 24.600 | 53.68 | 5.5 | ... | 0.4 | 0 | 0.2 | 0.0 | 4.4 | 41.936 | 0.4 | 0.5 | 8.3872 | 1 |
| 2 | 2.72 | 11 | 3.11 | 0.6 | 1.866 | 113.97 | 0.6 | 68.382 | 117.08 | 5.5 | ... | 0.4 | 0 | 0.2 | 0.0 | 4.4 | 88.832 | 0.4 | 0.5 | 17.7664 | 1 |
| 3 | 3.41 | 8 | 1.12 | 0.4 | 0.448 | 0.00 | 0.2 | 0.000 | 1.12 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 2.2 | 1.848 | 0.4 | 0.5 | 0.3696 | 0 |
| 4 | 55.57 | 9 | 1.06 | 0.4 | 0.424 | 0.00 | 0.2 | 0.000 | 1.06 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 2.2 | 1.824 | 0.4 | 0.5 | 0.3648 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 615 | 1.85 | 19 | 4.04 | 0.6 | 2.424 | 0.00 | 0.2 | 0.000 | 4.04 | 5.0 | ... | 1.2 | 0 | 0.2 | 0.0 | 2.8 | 4.782 | 1.2 | 0.5 | 2.8692 | 1 |
| 616 | 3.89 | 37 | 4.18 | 0.6 | 2.508 | 4.83 | 0.2 | 0.966 | 9.01 | 5.5 | ... | 0.4 | 0 | 0.2 | 0.0 | 3.2 | 14.492 | 0.4 | 0.5 | 2.8984 | 1 |
| 617 | 3.89 | 15 | 1.00 | 0.4 | 0.400 | 0.00 | 0.2 | 0.000 | 1.00 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 2.2 | 1.872 | 0.4 | 0.5 | 0.3744 | 0 |
| 618 | 55.57 | 6 | 2.24 | 0.6 | 1.344 | 7.26 | 0.6 | 4.356 | 9.50 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 3.6 | 7.148 | 0.4 | 0.5 | 1.4296 | 1 |
| 619 | 55.57 | 8 | 2.41 | 0.6 | 1.446 | 4.69 | 0.6 | 2.814 | 7.10 | 5.0 | ... | 0.4 | 0 | 0.2 | 0.0 | 3.6 | 5.710 | 0.4 | 0.5 | 1.1420 | 1 |
620 rows × 27 columns
Out[231]:
| Score_A | Score_B | |
|---|---|---|
| Risk | ||
| 0 | 0.262234 | 0.225532 |
| 1 | 0.490164 | 0.444262 |
100. pose값에 따른 각 motion컬럼의 중간값의 가장 큰 차이를 보이는 motion컬럼은 어디이며 그값은?¶
In [242]:
# 테이터 설명 : 센서데이터로 동작 유형 분류
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/muscle/train.csv')
display(df)
target = df.groupby('pose').median().T
abs(target[0] - target[1]).sort_values(ascending=False).head(1)
| motion_0 | motion_1 | motion_2 | motion_3 | motion_4 | motion_5 | motion_6 | motion_7 | motion_8 | motion_9 | ... | motion_55 | motion_56 | motion_57 | motion_58 | motion_59 | motion_60 | motion_61 | motion_62 | motion_63 | pose | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | -6.0 | 8.0 | 5.0 | 6.0 | -12.0 | -27.0 | 5.0 | 24.0 | -8.0 | -5.0 | ... | -1.0 | -3.0 | -6.0 | -9.0 | -7.0 | 36.0 | 68.0 | 3.0 | -3.0 | 1 |
| 1 | -32.0 | -3.0 | -4.0 | -5.0 | -1.0 | 16.0 | 0.0 | -5.0 | 42.0 | 2.0 | ... | -17.0 | -12.0 | -1.0 | -1.0 | 0.0 | -26.0 | -11.0 | -4.0 | -9.0 | 1 |
| 2 | 35.0 | -2.0 | -1.0 | 1.0 | -25.0 | -16.0 | -3.0 | -20.0 | 10.0 | 1.0 | ... | 6.0 | -65.0 | 6.0 | -10.0 | -31.0 | -19.0 | -3.0 | -47.0 | -17.0 | 0 |
| 3 | -15.0 | -6.0 | -3.0 | -5.0 | 27.0 | 37.0 | -2.0 | -2.0 | 19.0 | 5.0 | ... | 2.0 | 11.0 | 0.0 | -2.0 | -4.0 | -7.0 | 15.0 | 3.0 | 14.0 | 1 |
| 4 | 60.0 | 3.0 | 0.0 | -7.0 | -6.0 | -10.0 | -6.0 | 7.0 | -11.0 | -4.0 | ... | -12.0 | 17.0 | -3.0 | 1.0 | 2.0 | -2.0 | 20.0 | 18.0 | 10.0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 4645 | 40.0 | -8.0 | -14.0 | -27.0 | 10.0 | 12.0 | -35.0 | 12.0 | -21.0 | 1.0 | ... | 84.0 | -1.0 | 2.0 | -1.0 | -1.0 | -9.0 | -21.0 | -95.0 | -90.0 | 0 |
| 4646 | -35.0 | -4.0 | -6.0 | 0.0 | -4.0 | -11.0 | -24.0 | -27.0 | 46.0 | 12.0 | ... | -2.0 | -2.0 | -1.0 | -3.0 | 2.0 | 5.0 | 36.0 | 51.0 | 6.0 | 0 |
| 4647 | -34.0 | -17.0 | -4.0 | 10.0 | 14.0 | -22.0 | -6.0 | -24.0 | -17.0 | 26.0 | ... | -8.0 | -23.0 | -26.0 | -6.0 | -4.0 | 10.0 | -13.0 | -33.0 | -14.0 | 0 |
| 4648 | 21.0 | 3.0 | 0.0 | -15.0 | 5.0 | 2.0 | 48.0 | 22.0 | -22.0 | 2.0 | ... | -7.0 | -2.0 | 3.0 | -4.0 | -25.0 | 12.0 | 0.0 | 10.0 | -33.0 | 0 |
| 4649 | 3.0 | 31.0 | 0.0 | -6.0 | -16.0 | 2.0 | -38.0 | -35.0 | -19.0 | -17.0 | ... | 9.0 | -3.0 | -10.0 | -9.0 | 14.0 | -1.0 | -1.0 | -31.0 | -18.0 | 0 |
4650 rows × 65 columns
Out[242]:
motion_54 4.0 dtype: float64
101. 정보(row수)가 가장 많은 상위 3차종의 price값의 각 평균값은?¶
In [256]:
# 데이터 설명 : 현대차량가격 분류문제
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/hyundai/train.csv')
display(df.head())
print(df['model'].value_counts().index[:3])
target = df.loc[df['model'].isin(df['model'].value_counts().index[:3])].groupby('model').price.mean().to_frame()
target
| model | year | price | transmission | mileage | fuelType | tax(£) | mpg | engineSize | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | Tucson | 2016 | 12795 | Manual | 36263 | Diesel | 30 | 61.7 | 1.7 |
| 1 | I10 | 2012 | 3995 | Manual | 22089 | Petrol | 20 | 61.4 | 1.2 |
| 2 | I30 | 2019 | 24000 | Manual | 555 | Petrol | 145 | 34.0 | 2.0 |
| 3 | Tucson | 2017 | 12995 | Manual | 32147 | Diesel | 30 | 61.7 | 1.7 |
| 4 | Tucson | 2018 | 14991 | Semi-Auto | 32217 | Diesel | 150 | 57.6 | 1.7 |
Index([' Tucson', ' I10', ' I30'], dtype='object')
Out[256]:
| price | |
|---|---|
| model | |
| I10 | 7646.137891 |
| I30 | 11651.821759 |
| Tucson | 15805.441373 |
102. Outcome 값에 따른 각 그룹의 각 컬럼의 평균 차이를 구하여라¶
In [278]:
# 데이터 설명 : 당뇨여부 판단하기
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/diabetes/train.csv')
display(df.head())
target = df.groupby('Outcome').mean().diff().iloc[1,:]
target
| Pregnancies | Glucose | BloodPressure | SkinThickness | Insulin | BMI | DiabetesPedigreeFunction | Age | Outcome | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 3 | 102 | 74 | 0 | 0 | 29.5 | 0.121 | 32 | 0 |
| 1 | 2 | 144 | 58 | 33 | 135 | 31.6 | 0.422 | 25 | 1 |
| 2 | 5 | 136 | 82 | 0 | 0 | 0.0 | 0.640 | 69 | 0 |
| 3 | 13 | 145 | 82 | 19 | 110 | 22.2 | 0.245 | 57 | 0 |
| 4 | 1 | 117 | 60 | 23 | 106 | 33.8 | 0.466 | 27 | 0 |
Out[278]:
Pregnancies 1.574159 Glucose 29.943995 BloodPressure 3.202079 SkinThickness 2.952033 Insulin 33.398645 BMI 4.541437 DiabetesPedigreeFunction 0.143646 Age 5.866939 Name: 1, dtype: float64
103. 매년 5월달의 open가격의 평균값을 데이터 프레임으로 표현하라¶
In [291]:
# 데이터 설명 : 넷플릭스 주식데이터
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/nflx/NFLX.csv')
display(df.head())
df['Date'] = pd.to_datetime(df['Date'])
target = df.loc[df['Date'].dt.month==5].groupby(df['Date'].dt.year).Open.mean().to_frame()
target
| Date | Open | High | Low | Close | Adj Close | Volume | |
|---|---|---|---|---|---|---|---|
| 0 | 2002-05-23 | 1.156429 | 1.242857 | 1.145714 | 1.196429 | 1.196429 | 104790000 |
| 1 | 2002-05-24 | 1.214286 | 1.225000 | 1.197143 | 1.210000 | 1.210000 | 11104800 |
| 2 | 2002-05-28 | 1.213571 | 1.232143 | 1.157143 | 1.157143 | 1.157143 | 6609400 |
| 3 | 2002-05-29 | 1.164286 | 1.164286 | 1.085714 | 1.103571 | 1.103571 | 6757800 |
| 4 | 2002-05-30 | 1.107857 | 1.107857 | 1.071429 | 1.071429 | 1.071429 | 10154200 |
Out[291]:
| Open | |
|---|---|
| Date | |
| 2002 | 1.155833 |
| 2003 | 1.641497 |
| 2004 | 4.261143 |
| 2005 | 1.951905 |
| 2006 | 4.163571 |
| 2007 | 3.159351 |
| 2008 | 4.435034 |
| 2009 | 5.790571 |
| 2010 | 14.417071 |
| 2011 | 34.650272 |
| 2012 | 10.523247 |
| 2013 | 31.936429 |
| 2014 | 51.121292 |
| 2015 | 85.057429 |
| 2016 | 92.705715 |
| 2017 | 158.255455 |
| 2018 | 329.779541 |
| 2019 | 359.664548 |
| 2020 | 433.880499 |
| 2021 | 496.923996 |
104. Tm 컬럼은 각 팀의 이름을 의미한다. TOR팀의 평균나이를 소수 4째 자리까지 구하여라¶
In [300]:
# 데이터 설명 : nba선수 능력치 데이터
import pandas as pd
df=pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/nba/nba.csv',encoding='latin',sep=';')
display(df.head())
target = df.loc[df['Tm']=='TOR'].Age.mean()
print(round(target,4))
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
24.8696
105. Pos 컬럼은 포지션을 의미한다. 전체 선수 중 최소나이대의 선수들을 필터하고 그들 중 가장 많은 포지션은 무엇인지 확인하라¶
In [308]:
target = df.loc[df['Age'] == df['Age'].min()]
target['Pos'].value_counts().index[0]
Out[308]:
'SG'
106. 선수들의 이름은 first_name+ 공백 + last_name으로 이루어져 있다. 가장 많은 first_name은 무엇이며 몇 회 발생하는지 확인하라¶
In [345]:
display(df.head())
target = df['Player'].map(lambda x:x.split(' ')[0]).value_counts().head(1)
target
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[345]:
Justin 14 Name: Player, dtype: int64
107. PTS컬럼은 경기당 평균득점수 이다. 각포지션별로 경기당 평균득점수의 평균을 구하여라¶
In [346]:
display(df.head())
target = df.groupby('Pos').PTS.mean().sort_values(ascending=False)
target
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[346]:
Pos PG-SG 22.000000 C-PF 12.850000 SG-PG 9.525000 SF-SG 8.660000 PF-SF 8.500000 PG 8.325161 SG 7.810553 PF 7.737500 C 7.690769 SG-SF 7.360000 SF 7.270253 Name: PTS, dtype: float64
108. PTS컬럼은 경기당 평균득점수 이다. 각포지션별로 경기당 평균득점수의 평균을 구하여라¶
In [347]:
display(df.head())
target = df.groupby('Pos').PTS.mean().sort_values(ascending=False)
target
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[347]:
Pos PG-SG 22.000000 C-PF 12.850000 SG-PG 9.525000 SF-SG 8.660000 PF-SF 8.500000 PG 8.325161 SG 7.810553 PF 7.737500 C 7.690769 SG-SF 7.360000 SF 7.270253 Name: PTS, dtype: float64
109. G컬럼은 참여한 경기의 숫자이다. 각 팀별로 가장 높은 경기참여 수를 가진 선수들의 경기 참여 숫자의 평균을 구하여라¶
In [348]:
display(df.head())
target = df.groupby('Tm').G.max()
target.mean()
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[348]:
77.51612903225806
110. Tm의 값이 MIA이며 Pos는 C또는 PF인 선수의 MP값의 평균은?¶
In [349]:
display(df.head())
target = df.loc[(df['Tm']=='MIA') & (df['Pos'].isin(['C','PF']))].MP.mean()
print(round(target,4))
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
16.7875
111. 전체 데이터중 G의 평균값의 1.5배 이상인 데이터들만 추출했을때 3P값의 평균은?¶
In [355]:
display(df.head())
target= df.loc[df['G']>=(df['G'].mean()*1.5)]['3P'].mean()
target
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[355]:
1.3853658536585358
112. Age의 평균 이상인 그룹과 평균 미만인 그룹간의 G값의 평균의 차이는?¶
In [361]:
display(df.head())
target_down_age = df.loc[df['Age']<df['Age'].mean()].G.mean()
target_up_age = df.loc[df['Age']>=df['Age'].mean()].G.mean()
print(target_up_age - target_down_age)
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
3.787674551781862
113. 평균나이가 가장 젊은 팀은 어디인가¶
In [366]:
display(df.head())
target = df.groupby('Tm').Age.mean().sort_values(ascending=True)
target.index[0]
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[366]:
'MEM'
114. Pos그룹별 평균 MP값을 구하여라¶
In [370]:
display(df.head())
target = df.groupby('Pos').MP.mean().sort_values(ascending=False)
target
| Rk | Player | Pos | Age | Tm | G | GS | MP | FG | FGA | ... | FT% | ORB | DRB | TRB | AST | STL | BLK | TOV | PF | PTS | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | Precious Achiuwa | C | 22 | TOR | 73 | 28 | 23.6 | 3.6 | 8.3 | ... | 0.595 | 2.0 | 4.5 | 6.5 | 1.1 | 0.5 | 0.6 | 1.2 | 2.1 | 9.1 |
| 1 | 2 | Steven Adams | C | 28 | MEM | 76 | 75 | 26.3 | 2.8 | 5.1 | ... | 0.543 | 4.6 | 5.4 | 10.0 | 3.4 | 0.9 | 0.8 | 1.5 | 2.0 | 6.9 |
| 2 | 3 | Bam Adebayo | C | 24 | MIA | 56 | 56 | 32.6 | 7.3 | 13.0 | ... | 0.753 | 2.4 | 7.6 | 10.1 | 3.4 | 1.4 | 0.8 | 2.6 | 3.1 | 19.1 |
| 3 | 4 | Santi Aldama | PF | 21 | MEM | 32 | 0 | 11.3 | 1.7 | 4.1 | ... | 0.625 | 1.0 | 1.7 | 2.7 | 0.7 | 0.2 | 0.3 | 0.5 | 1.1 | 4.1 |
| 4 | 5 | LaMarcus Aldridge | C | 36 | BRK | 47 | 12 | 22.3 | 5.4 | 9.7 | ... | 0.873 | 1.6 | 3.9 | 5.5 | 0.9 | 0.3 | 1.0 | 0.9 | 1.7 | 12.9 |
5 rows × 30 columns
Out[370]:
Pos PG-SG 37.200000 PF-SF 27.300000 C-PF 25.350000 SG-PG 22.950000 SF-SG 20.340000 SG-SF 19.620000 PG 19.547742 SG 18.554271 PF 17.937500 SF 17.514557 C 16.990000 Name: MP, dtype: float64
'빅데이터분석기사 준비' 카테고리의 다른 글
| 빅분기 2유형 문제연습 (0) | 2023.05.25 |
|---|---|
| 빅분기6장(앙상블(Ensemble)) (0) | 2023.05.21 |
| 빅분기6장(의사결정나무(Decision Tree)) (0) | 2023.05.17 |
| 빅분기6장(k-최근접 이웃(KNN)) (0) | 2023.05.15 |
| 빅분기6장(서포트 벡터 머신) (0) | 2023.05.12 |