본문 바로가기

코딩으로 익히는 Python/Numpy

[Python] 07. numpy 종합 예제 : matplotlib,시각화,np.loadtxt(),plt.show(),np.array(),zip(),np.quantile()

728x90
반응형
SMALL
import numpy as np

 

데이터 불러오기 (np.loadtxt)

 

python 파일 경로에 data폴더 만든 후 다음의 births.txt 파일 넣어놓기

births.txt
0.00MB

 

birth = np.loadtxt( 'data/births.txt', delimiter=',', dtype=np.int64) 
# data폴더 안의 births.txt파일 ','로 구분하여 load하기

 

birth.shape # 132행 3열
[OUT] :

(132, 3)

 

 

birth # 연도, 남아수, 여아수로 구성되어있음
[OUT] :

array([[   1880,   90993,  110491],
       [   1881,   91954,  100745],
       [   1882,  107850,  113688],
       [   1883,  112321,  104629],
       [   1884,  129022,  114445],
       [   1885,  133055,  107800],
       [   1886,  144535,  110784],
       [   1887,  145982,  101414],
       [   1888,  178627,  120853],
       [   1889,  178366,  110584],
       [   1890,  190377,  111025],
       [   1891,  185482,  101196],
       [   1892,  212346,  122037],
       [   1893,  212906,  112317],
       [   1894,  222922,  115772],
       [   1895,  233630,  117398],
       [   1896,  237920,  119570],
       [   1897,  234202,  112758],
       [   1898,  258770,  122693],
       [   1899,  233023,  106212],
       [   1900,  299828,  150499],
       ...
       [   2011, 1753500, 1893230]])

데이터 시각화하기 (matplotlib)

import matplotlib.pyplot as plt # 시각화와 관련된 라이브러리

 

 # matplotlib 연습
a = np.array([1,2,3,4,5])
b = np.array([11,22,33,44,55])

plt.plot(a,b , 'bo--')
plt.bar(a,b) # bar chart 만들기

plt.title( 'kor' ) # chart의 제목 : 'kor'
plt.xlabel('Students_num') # x축 label : 'Students_num'
plt.ylabel('Score') # y축 label : 'Score'
plt.show()


문제

#1. 남아 , 여아 출생 평균을 구하시오.

#2. 2000년대 이후 데이터를 구하시오.
년도   남아   여아
==============
2000     xx     xx

#3. 남아출생이 가장 많은 연도와 남아수를 구하시오.

#4. 남아출생이 가장 많은 top 5를 구하시오.(연도와 남아수)

#5. 남아율(%)을 구하고 각 연도별 남아수가 차지하는비율을 데이터로 보여주시오.
남아수    여아수    남아율
===================
..

#6. 2000년도 이후데이터 에 대해 출생량을 구하고 남아수가 1800000 이상이면 '많음'아니면 '적음'이라고 보여 주시오.
연도 남아수 출생량
2000   1233   '많음'
2001   1234   '적음'

#7. 1800년대, 1900년대, 2000년대 각 남아,여아수 평균을 구하시오.

#8. 여아 25%~75%사이의 값을 구하시오.

#9. 2000년대 남아데이터를 바 차트로 그리시오.

 

※ 스스로 풀어본 후 아래 Solution 확인하기


Solution

#1. 남아 ,여아 출생 평균을 구하시오.

birth
print( "남아 평균:",int(birth[:,1].mean()) ) #남아
print( "여아 평균:",int(birth[:,2].mean()) ) #여아
[OUT] :

남아 평균: 1225776
여아 평균: 1245399


#2. 2000년대 이후 데이터를 구하시오.
년도   남아   여아
==============
2000     xx     xx

print('연도','남아', '여아',sep='\t')
print('='*23)
for y,m,f in birth[ birth[:,0] >= 2000 ]:
    print( y,m,f,sep='\t')
[OUT] :

연도	남아	여아
=======================
2000	1814601	1962406
2001	1799049	1941251
2002	1795206	1939815
2003	1825359	1973434
2004	1834145	1982794
2005	1845379	1994841
2006	1898463	2052377
2007	1919408	2072139
2008	1887234	2036289
2009	1832925	1979303
2010	1772738	1913851
2011	1753500	1893230


#3. 남아출생이 가장 많은 연도와 남아수를 구하시오.

# birth[:,1].argmax() : 남아수가 가장 많은 값의 index반환
# birth[birth[:,1].argmax()][[0,1]] : 남아수가 가장 많은 값의 연도와 남아수 리스트 형태로 반환
y = birth[birth[:,1].argmax()][[0,1]][0] 
b = birth[birth[:,1].argmax()][[0,1]][1]
print('연도','남아수',sep='\t')
print(y,b,sep='\t')
[OUT] :

연도	남아수
1957	2044160


#4. 남아출생이 가장 많은 top 5를 구하시오.(연도와 남아수)

top5_boys = np.sort( birth[:,1] )[-1:-6:-1]
print('연도 남아수')
print('='*12)
for i in birth:
    for j in top5_boys:
        if i[1] == j:
            print(i[0],j)
[OUT] :

연도 남아수
============
1957 2044160
1958 2010884
1959 2023044
1960 2022093
1961 2017316


#5. 남아율(%) 을 구하고 각 연도별 남아수가 차지하는비율을 데이터로 보여주시오.
남아수    여아수    남아율
===================
..

boys_ratio = (  birth[:,1]/ (birth[:,1]+birth[:,2])  ).round(2)
print( '년도','남아', '여아', '남아율',sep='\t')
print('=='*14)
for year, boy , girl , boy_ratio in zip(birth[:,0], birth[:,1],birth[:,2], boys_ratio):
    print(year,boy, girl, boy_ratio,sep='\t')
[OUT] :

년도	남아	여아	남아율
============================
1880	90993	110491	0.45
1881	91954	100745	0.48
1882	107850	113688	0.49
1883	112321	104629	0.52
1884	129022	114445	0.53
1885	133055	107800	0.55
1886	144535	110784	0.57
1887	145982	101414	0.59
1888	178627	120853	0.6
1889	178366	110584	0.62
1890	190377	111025	0.63
1891	185482	101196	0.65
1892	212346	122037	0.64
1893	212906	112317	0.65
1894	222922	115772	0.66
1895	233630	117398	0.67
...
2011	1753500	1893230	0.48


#6. 2000년도 이후데이터 에 대해 출생량 을 구하고 남아수가 1800000 이상이면 '많음'아니면 '적음'이라고 보여 주시오.
연도 남아수 출생량
2000   1233   '많음'
2001   1234   '적음'

aft_2000 = birth [ birth[:,0] >= 2000 ]
boys = aft_2000[:,1]
amount = np.where( aft_2000[:,1] >= 1800000 , '많음', '적음')
for year, boy, amt in zip( aft_2000[:,0],aft_2000[:,1], amount):
    print(year, boy, amt)
[OUT] :

2000 1814601 많음
2001 1799049 적음
2002 1795206 적음
2003 1825359 많음
2004 1834145 많음
2005 1845379 많음
2006 1898463 많음
2007 1919408 많음
2008 1887234 많음
2009 1832925 많음
2010 1772738 적음
2011 1753500 적음

 

#7. 1800년대, 1900년대, 2000년대각 남아, 여아수 평균을 구하시오.

print('1800년대')
print('남아수 평균, 여아수 평균')
kids_1800s = birth[ (birth[:,0] >= 1800) & (birth[:,0]< 1900) ][:,1:]
print(kids_1800s.mean( axis=0 )[0],kids_1800s.mean( axis=0 )[1])
[OUT] :

1800년대
남아수 평균, 여아수 평균
176714.15 111820.55

 

print('1900년대')
print('남아수 평균, 여아수 평균')
kids_1900s = birth[ (birth[:,0] >= 1900) & (birth[:,0]< 2000) ][:,1:]
print(kids_1900s.mean( axis=0 )[0],kids_1900s.mean( axis=0 )[1])
[OUT] :

1900년대
남아수 평균, 여아수 평균
1362901.51 1384145.55

 

print('2000년대')
print('남아수 평균, 여아수 평균')
kids_2000s = birth[ birth[:,0] >= 2000 ][:,1:]
print(kids_2000s.mean( axis=0 )[0],kids_2000s.mean( axis=0 )[1])
[OUT] :

2000년대
남아수 평균, 여아수 평균
1831500.5833333333 1978477.5


#8. 여아 25%~75% 사이의 값을 구하시오.

girls_q25 = np.quantile( birth[:,2] ,0.25 )
girls_q75 = np.quantile( birth[:,2] ,0.75 )
birth [ (birth[:,2] >= girls_q25) & (birth[:,2] <= girls_q75 ) ][:,[0,2]]
[OUT] :

array([[   1913,  512557],
       [   1914,  654762],
       [   1915,  848603],
       [   1916,  890099],
       [   1917,  925511],
       [   1918, 1013537],
       [   1919,  980149],
       [   1920, 1064463],
       [   1921, 1101457],
       [   1922, 1088287],
       [   1923, 1096168],
       [   1924, 1132751],
       [   1925, 1115958],
       [   1926, 1110505],
       [   1927, 1126717],
       [   1928, 1107518],
       [   1929, 1075313],
       ...
       [   2011, 1893230]])


#9. 2000년대 남아 데이터를 바 차트로 그리시오.

boys_2000s = birth[ birth[:,0] >= 2000 ][:,0:2]

plt.bar( boys_2000s[:,0] ,boys_2000s[:,1], color='salmon')
plt.xlabel('year')
plt.ylabel('boysBirth')
plt.show()


Review
- cheer up
728x90
반응형
LIST