빅데이터 분석기사/작업 유형 1 문제 풀이

1번 ~10번 풀이 drop_duplicates, size, day_name, weekday

유방울 2023. 5. 29. 13:31

1

answer =list(df.loc[df.channelId.isin(df.channelId.value_counts().head(10).index)].channelTitle.unique())
print(answer)

2

answer = list(df[df['dislikes'] > df['likes']].channelTitle.unique())
print(answer)

['핫도그TV', 'ASMR 애정TV', '하얀트리HayanTree', '양팡 YangPang', '철구형 (CHULTUBE)', '왜냐맨하우스', '(MUTUBE)와꾸대장봉준', '오메킴TV', '육지담', 'MapleStory_KR', 'ROAD FIGHTING CHAMPIONSHIP', '사나이 김기훈', '나혼자산다 STUDIO', 'Gen.G esports']

3

# q3
df['channelId'].value_counts()

UCszFjh7CEfwDb7UUGb4RzCQ    372
UCtm_QoN2SIxwCE-59shX7Qg    318
UClzB2iZ5jPoTNz0S-QU6Wiw    318
UCaKod3X1Tn4c7Ci0iUKcvzQ    313
UCiwQRG2sCcfjKkgxMEdJGPg    293
                           ... 
UCRnEWJKVc5FpC-9Z3CBt2ZQ      1
UCTt-fHgG4s9PAeQSDhFdZGA      1
UCLp6fbMCDB9nGl53FGbzUBA      1
UC93Zlfnj_ni8K6fL3mzbpqg      1
UC55V69aW9X1aHFpjCWRL_iQ      1
Name: channelId, Length: 1770, dtype: int64

drop_duplicates()

중복된 값 제거!

df[['channelTitle','channelId']].drop_duplicates().channelId.value_counts()

UCtQYhzJWFai1y30UIA3uwYQ    3
UC98TOxKQk4aLcx0EjIK0LkQ    3
UCms8Ge7H1ZGgw6nV94fUhUQ    2
UC3IZKseVpdzPSBaWxBxundA    2
UCdpbqw5DPdBfaeByMF2Re0g    2
                           ..
UChI3EXzhAkRszawlMageKvQ    1
UCI33Ji_XMO5RG6gvGIXWm7g    1
UCjF1QO9lFMggd8X_L1ZfRMg    1
UCyPwRgc3gQGqhk6RoGS50Ug    1
UCQV0Qy_1fqzbHloomT2JHfQ    1
Name: channelId, Length: 1770, dtype: int64
change = df[['channelTitle','channelId']].drop_duplicates().channelId.value_counts()
target = change[change>1]
print(len(target))

71

dt.year 사용시 에러 발생!

# 4
# 일요일 영상 추출
# datetime 타입으로 바꿔야 함
df['trending_date2'].dt.year

AttributeError: Can only use .dt accessor with datetimelike values

타입 확인 -> object 임

df.dtypes

title             object
channelTitle      object
categoryId         int64
view_count         int64
likes              int64
dislikes           int64
comment_count      int64
channelId         object
trending_date2    object
dtype: object

pd.to_datetime() 으로 데이터타입 변경

import pandas as pd
df['trending_date2'] = pd.to_datetime(df['trending_date2'])
df['trending_date2']

0       2021-01-01
1       2021-01-01
2       2021-01-01
3       2021-01-01
4       2021-01-01
           ...    
60394   2021-10-19
60395   2021-10-19
60396   2021-10-19
60397   2021-10-19
60398   2021-10-19
Name: trending_date2, Length: 60399, dtype: datetime64[ns]

요일 추출 way 1

dt 엑세서 메서드

weekday 

monday 0 ~ sunday 6 (월 0 , 화1 , 수 2, 목 3,금 4,토 5 ,일 6)

 

# monday 0 ~ sunday 6
# 일요일 = 6
df['trending_date2'].dt.weekday

0        4
1        4
2        4
3        4
4        4
        ..
60394    1
60395    1
60396    1
60397    1
60398    1
Name: trending_date2, Length: 60399, dtype: int64

way 2 

day_name() = 'Sunday'

# index[0] 가장많은 영상의 첫번째 영상!
# dt.day_name() == 'Sunday' 도 가능

df['trending_date2'] = pd.to_datetime(df['trending_date2'])
answer = df[df['trending_date2'].dt.weekday == 6].categoryId.value_counts().index[0]
print(answer)

24

 

count : 결측치의 개수 포함하지 않음

size : 결측치 개수 포함

as_index = False

# 5
# df['trending_date2'].dt.weekday
# size() 해당 칼럼만 !vs count(): 모든 칼럼의 count임
# as_index = False : SQL st
df.groupby([df['trending_date2'].dt.day_name(),'categoryId'], as_index=False).size()

	trending_date2	categoryId	size
0	Friday	1	243
1	Friday	2	120
2	Friday	10	833
3	Friday	15	187
4	Friday	17	633
...	...	...	...
100	Wednesday	25	468
101	Wednesday	26	385
102	Wednesday	27	212
103	Wednesday	28	165
104	Wednesday	29	12
105 rows × 3 columns
df.groupby([df['trending_date2'].dt.day_name(),'categoryId']).size()

trending_date2  categoryId
Friday          1             243
                2             120
                10            833
                15            187
                17            633
                             ... 
Wednesday       25            468
                26            385
                27            212
                28            165
                29             12
Length: 105, dtype: int64
# display 
group = df.groupby([df['trending_date2'].dt.day_name(),'categoryId'], as_index=False).size()
answer = group.pivot(index ='categoryId', columns='trending_date2')
display(answer)

	size
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
# 0 제거 
target2 = df.loc[df.view_count!=0]
# 원본 보존 -
t = target2.copy()
# 비율 계산한 칼럼
t['ratio'] = (target2['comment_count']/target2['view_count']).dropna()

result = t.sort_values('ratio', ascending = False).iloc[0].title
print(result)

60분 동안 댓글이 달리지 않으면, 영상이 삭제됩니다. (챌린지)
# 8
ratio = (df['comment_count'] / df['view_count']).dropna().sort_values()
ratio

8319     0.0
49317    0.0
44708    0.0
39755    0.0
39769    0.0
        ... 
526      inf
1180     inf
957      inf
740      inf
297      inf
Length: 60392, dtype: float64
df.iloc[ratio[ratio!=0].index[0]]

title             Join the BTS #PermissiontoDance Challenge only...
channelTitle                                                YouTube
categoryId                                                       27
view_count                                                 46458563
likes                                                             0
dislikes                                                          0
comment_count                                                     1
channelId                                  UCBR8-60-B28hp2BmDPdntcQ
trending_date2                                  2021-08-09 00:00:00
Name: 46005, dtype: object
ratio = (df['comment_count'] / df['view_count']).dropna().sort_values()
ratio[ratio!=0].index[0]

result= df.iloc[ratio[ratio!=0].index[0]].title
print(result)

Join the BTS #PermissiontoDance Challenge only on YouTube #Shorts
# q8
target = df[(df['likes'] != 0) & (df['dislikes'] != 0)]
num = target.copy()
num['ratio'] = (num['dislikes']/num['likes']).dropna()
result = num.sort_values('ratio').iloc[0].title
print(result)

[줌터뷰] *최초공개* 사부작즈🐰🐶의 비공식 이름은 아이라인즈? 꿀조합 티키타카 가득한 NCT 127 도영&정우의 줌터뷰
#q9
# channelId 은 채널 고유 아이디
# 채널 아이디가 많이 아농 것 -> 트렌드 영상이 많이 나옴
answer = df.loc[df.channelId == df.channelId.value_counts().index[0]].channelTitle.unique()[0]
print(answer)

짤툰
# q10
# 20회이상 인기동영상 리스트에 포함됨
# 동영상 숫자?
answer = (df[['title','channelId']].value_counts()>20).sum()
print(answer)

22

way1 : 읽고/쓰기 가능, 칼럼라벨이 문자열, 숫자 가능, 문자열에 공백, 특수문자도 가능

way2 : 읽기만 가능, 칼럼라벨이 반드시 이름규칙을 만족해야 함!

 

이름규칙 : 숫자로 시작, '_'을 제외한 공백 및 특수문자 사용 불가능

# way 1
df['channelId'].value_counts()

# way2
df.channelId.value_counts()