본문 바로가기
개발일지/Pandas

pandas 틀린문제 9, groupby, unstack, nlargest

by 개발에정착하고싶다 2022. 8. 12.
320x100

이번 섹션 문제도 거의 멸망에 가까운 지경이다.

하지만 성취감은 이전보다 훨씬 낮다.

그도 그럴게 아예 한개도 모르겠진 않고, 부분적으로 모르는 것들이 좀씩 나와서 못하겠더라.

모자란 부분은 다듬어 가보도록 하자.

 

# 기초

#run the cell
cars.head()

'''
mpg	cylinders	displacement	horsepower	weight	acceleration	model_year	origin	name
0	18.0	8	307.0	130.0	3504	12.0	70	usa	chevrolet chevelle malibu
1	15.0	8	350.0	165.0	3693	11.5	70	usa	buick skylark 320
2	18.0	8	318.0	150.0	3436	11.0	70	usa	plymouth satellite
3	16.0	8	304.0	150.0	3433	12.0	70	usa	amc rebel sst
4	17.0	8	302.0	140.0	3449	10.5	70	usa	ford torino
'''
# 문제1. Group cars by the column origin and calculate the mean/average mpg for each origin (mean mpg for usa, for europe and for japan)!
# Who built the least fuel efficient cars?

# 내가 문제를 잘못 이해한 것같다.
# 답으로는 맞았지만, 과정도 그렇고 정확히 다가가는 부분에 있어선 틀렸다고 볼 수 있다.

# 내 코드
cars.groupby('origin').mean() / cars.mpg.mean()

'''
	mpg	cylinders	displacement	horsepower	weight	acceleration	model_year
origin							
europe	1.186134	0.176790	4.641499	3.425911	103.055242	0.713904	3.224140
japan	1.294969	0.174414	4.367881	3.395147	94.461756	0.687750	3.293406
usa	0.854089	0.265750	10.457413	5.062774	142.972264	0.639337	3.215472
'''
# 답안 코드
cars.groupby('origin').mpg.mean()

'''
origin
europe    27.891429
japan     30.450633
usa       20.083534
Name: mpg, dtype: float64
'''


# 문제2. Group cars by the column model_year and calculate the mean/average mpg for each model_year (mean mpg for 70, 71, 72,...)!
# Save the result in the variable mpg_by_year and round to two decimals!

# 이것도 문제를 잘못 이해한 것같다.

# 내코드 
mpg_by_year = round(cars.groupby('model_year').mean() / cars.mpg.mean(), 2)

'''
    mpg	cylinders	displacement	horsepower	weight	acceleration
model_year						
70	0.75	0.29	11.97	6.29	143.43	0.55
71	0.90	0.24	8.92	4.55	127.39	0.64
72	0.80	0.25	9.29	5.11	137.69	0.64
73	0.73	0.27	10.92	5.55	145.40	0.61
74	0.97	0.22	7.30	4.01	122.39	0.69
75	0.86	0.24	8.74	4.30	135.10	0.68
76	0.92	0.24	8.41	4.30	130.93	0.68
77	0.99	0.23	8.14	4.47	127.47	0.66
78	1.02	0.23	7.56	4.24	121.70	0.67
79	1.07	0.25	8.79	4.30	129.93	0.67
80	1.43	0.18	4.93	3.30	103.62	0.72
81	1.29	0.20	5.75	3.45	107.29	0.69
82	1.35	0.18	5.48	3.46	104.34	0.71
'''
# 답안 코드

mpg_by_year = cars.groupby('model_year').mpg.mean().round(2)

'''
model_year
70    17.69
71    21.25
72    18.71
73    17.10
74    22.70
75    20.27
76    21.57
77    23.38
78    24.06
79    25.09
80    33.70
81    30.33
82    31.71
Name: mpg, dtype: float64
'''


# 문제3. Group cars by the columns model_year and origin and return the mean mpg for each group!
# Save the resulting DataFrame in the variable mpg_year_origin! Column labels of mpg_year_origin shall be europe, japan & usa. Fill in the gaps!

# unstack의 개념을 모르니깐 이건 틀릴 수 밖에 없었나

# 내코드
mpg_year_origin = cars.groupby(['model_year', 'origin']).mpg.mean().round(2)

'''
model_year  origin
70          europe    25.20
            japan     25.50
            usa       15.27
71          europe    28.75
            japan     29.50
            usa       18.10
72          europe    22.00
            japan     24.20
            usa       16.28
73          europe    24.00
            japan     20.00
            usa       15.03
74          europe    27.00
            japan     29.33
            usa       18.33
75          europe    24.50
            japan     27.50
            usa       17.55
76          europe    24.25
            japan     28.00
            usa       19.43
77          europe    29.25
            japan     27.42
            usa       20.72
78          europe    24.95
            japan     29.69
            usa       21.77
79          europe    30.45
            japan     32.95
            usa       23.48
80          europe    37.29
            japan     35.40
            usa       25.91
81          europe    31.58
            japan     32.96
            usa       27.53
82          europe    40.00
            japan     34.89
            usa       29.45
Name: mpg, dtype: float64
'''
# 답안 코드
mpg_year_origin = cars.groupby(['model_year', 'origin']).mpg.mean().unstack().round(2)

'''

origin	europe	japan	usa
model_year			
70	25.20	25.50	15.27
71	28.75	29.50	18.10
72	22.00	24.20	16.28
73	24.00	20.00	15.03
74	27.00	29.33	18.33
75	24.50	27.50	17.55
76	24.25	28.00	19.43
77	29.25	27.42	20.72
78	24.95	29.69	21.77
79	30.45	32.95	23.48
80	37.29	35.40	25.91
81	31.58	32.96	27.53
82	40.00	34.89	29.45
'''


# 문제4. Group cars by model_year and origin and return mean, max and min mpg for all groups! Fill in the gaps!

cars.groupby(["model_year", "origin"]).mpg.agg(['mean', 'max', 'min']).unstack().round(2)

'''
mean	max	min
origin	europe	japan	usa	europe	japan	usa	europe	japan	usa
model_year									
70	25.20	25.50	15.27	26.0	27.0	22.0	24.0	24.0	9.0
71	28.75	29.50	18.10	30.0	35.0	28.0	27.0	25.0	12.0
72	22.00	24.20	16.28	26.0	28.0	28.0	18.0	19.0	11.0
73	24.00	20.00	15.03	29.0	22.0	23.0	19.0	18.0	11.0
74	27.00	29.33	18.33	31.0	32.0	28.0	24.0	24.0	13.0
75	24.50	27.50	17.55	29.0	33.0	23.0	22.0	24.0	13.0
76	24.25	28.00	19.43	29.5	33.0	29.0	16.5	19.0	13.0
77	29.25	27.42	20.72	36.0	33.5	33.5	21.5	21.5	15.0
78	24.95	29.69	21.77	43.1	39.4	36.1	16.2	21.1	17.5
79	30.45	32.95	23.48	37.3	34.1	35.7	25.4	31.8	15.5
80	37.29	35.40	25.91	44.3	46.6	32.1	29.8	23.7	19.1
81	31.58	32.96	27.53	34.5	39.1	39.0	28.1	24.2	17.6
82	40.00	34.89	29.45	44.0	38.0	38.0	36.0	31.0	22.0
'''

# 이건 풀어놓고도 신기해서 올려본다.
# 어떻게 풀었지?
# 아마 코드 가이드가 있어서 풀 수 있었던 것 같다.
# 그나저나, 강사님의 데이터프레임 필드값과 나의 데이터프레임 필드값이 미묘하게 다르네.


# 문제5. Next, return the columns __name__ and __mpg__ for the __two most fuel efficient cars__ for __each combination of model_year & origin__!
# First, create the user defined function get_most_efficient! Fill in the gaps!

# 구체적으로 모르겠다.
# 내 코드
# def get_most_efficient(group):
#    return group(n = 2, columns = "mpg").loc[:, ["name", "mpg"]]

# n = 이라고 나올때 눈치를 챘어야한다.

def get_most_efficient(group):
    return group.nlargest(n = 2, columns = 'mpg').loc[:,['name', 'mpg']]


# 문제6. Apply__ get_most_efficient on the appropriate __groupby object__! __Save__ the resulting DataFrame in the variable __most_eff__. __Fill in the gaps!__

# 사용자 정의 함수가 막히니 여기도 막히고, groupby안에 어떤 컬럼을 넣어줘야하는지도 모르겠더라.
# 내 코드 
cars.groupby(['name', 'mpg']).apply(get_most_efficient)
# 답안 코드

most_eff = cars.groupby(['model_year', 'origin']).apply(get_most_efficient)

'''
            name	mpg
model_year	origin			
70	europe	19	vw 1131 deluxe sedan	26.0
23	bmw 2002	26.0
japan	18	datsun pl510	27.0
14	toyota corona mark ii	24.0
usa	15	plymouth duster	22.0
...	...	...	...	...
82	europe	375	vw rabbit l	36.0
japan	383	honda civic	38.0
385	datsun 310 gx	38.0
usa	378	plymouth horizon miser	38.0
387	oldsmobile cutlass ciera (diesel)	38.0
78 rows × 2 columns
'''


# 문제7. Select the 2 most efficient cars from japan in 1980! Fill in the gaps! The most efficient car is...?

# 내 코드
# most_eff.loc[most_eff.nlargest[2, most_eff.origin == 'japan']]

# 답안 코드
most_eff.loc[(80, 'japan')]

# 이번에는 문제가 '일본'을 어떻게 선택해주느냐에 대해서 잘 모르겠었다.
# 그리고 2개의 가장 효과적인 차를 골라주라고 하는 nlargest에 대한 오더를 받았는데, 이걸 어떻게 구현할지도 잘 감이 안왔다.

'''
		name	mpg
model_year	origin		
80	japan	mazda glc	46.6
japan	honda civic 1500 gl	44.6
'''


# 문제8. First, group cars by model_year & origin and calculate the mean mpg for each group via the --- method to create the new column "group_mpg".
# Fill in the gaps!

# 표현에 유의 하자
# 답안 코드
cars["group_mpg"] = cars.groupby(["model_year", "origin"]).mpg.transform('mean').round(2)
300x250