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

pandas 판다스 틀린문제 10 crosstab, pivot_table

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

음... 좀처럼 나아진다는 느낌이 잘 들질 않긴 하다.

이번 섹션은 전체를 몰랐다고 봐도 무방하다.

 

#run the cell!
pivot.head()

'''
origin	europe	japan	usa
model_year			
70	25.20	25.500000	15.272727
71	28.75	29.500000	18.100000
72	22.00	24.200000	16.277778
73	24.00	20.000000	15.034483
74	27.00	29.333333	18.333333
'''
# 틀린문제1. Pivot mean_mpg! Resulting wide-format DataFrame shall have three columns europe, japan and usa. model_year shall be the index!
# Save new DataFrame in the variable pivot!

# 모르겠다. columns를 3개로 만들어 주고 싶었는데, 그게 origin에서 다 머금고 있기에 문제가 없는 건가.
# 내 원본 코드
# mean_mpg.pivot(index = 'model_year', columns = ['europe', 'japan', 'usa'])

# 답안 코드
pivot = mean_mpg.pivot(index = 'model_year', columns = 'origin', values = 'mpg')


# 문제2. Melt the DataFrame pivot from wide format back to long format! Fill in the gaps!

# 내코드
# pivot.melt(id_vars= 'model_year', value_vars= 'origin', var_name = 'mpg', value_name = 'Count')

# 답안 코드
pivot.melt(id_vars = 'model_year', value_vars = ['europe', 'japan', 'usa'], 
           var_name = 'origin', value_name = 'mpg')
           
           
'''

model_year	origin	mpg
0	70	europe	25.200000
1	71	europe	28.750000
2	72	europe	22.000000
3	73	europe	24.000000
4	74	europe	27.000000
5	75	europe	24.500000
6	76	europe	24.250000
7	77	europe	29.250000
8	78	europe	24.950000
9	79	europe	30.450000
10	80	europe	37.288889
11	81	europe	31.575000
12	82	europe	40.000000
13	70	japan	25.500000
14	71	japan	29.500000
15	72	japan	24.200000
16	73	japan	20.000000
17	74	japan	29.333333
18	75	japan	27.500000
19	76	japan	28.000000
20	77	japan	27.416667
21	78	japan	29.687500
22	79	japan	32.950000
23	80	japan	35.400000
24	81	japan	32.958333
25	82	japan	34.888889
26	70	usa	15.272727
27	71	usa	18.100000
28	72	usa	16.277778
29	73	usa	15.034483
30	74	usa	18.333333
31	75	usa	17.550000
32	76	usa	19.431818
33	77	usa	20.722222
34	78	usa	21.772727
35	79	usa	23.478261
36	80	usa	25.914286
37	81	usa	27.530769
38	82	usa	29.450000
'''
# 문제3. Return the number of cars for each combination of model_year and origin with pd.crosstab() (e.g. 5 cars from europe in 1970)!
# How many cars from usa are built in 1972?

# 내코드
# pd.crosstab(mean_mpg.model_year, mean_mpg.origin, margins = True, normalize = True)

# 답안 코드
pd.crosstab(cars.model_year, cars.origin)

'''
origin	europe	japan	usa
model_year			
70	5	2	22
71	4	4	20
72	5	5	18
73	7	4	29
74	6	6	15
75	6	4	20
76	8	4	22
77	4	6	18
78	6	8	22
79	4	2	23
80	9	13	7
81	4	12	13
82	2	9	20
'''
300x250