공부중/python

파이썬 입문 7일차

또돌근 2021. 2. 18. 21:09
반응형

1. excel _ 7

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 09:55:42 2021

@author: 2016005

excelex7.py : pandas를 이용하여 xls파일 읽기.
                출력되는 excel파일의 sheet를 여러개로 저장하기
                
                
                pandas를 이용하면
                xlsx나 xls나 별반 다르지 않다.
                자동으로 표로 만들어서 엑셀파일을 처리할 수 있다.
                자바로 하려면 코드량이 엄청날것이다.
                판다스는 매우 간단하다.
                자료에 대한 내용정렬 등에 상당히 잘 돼있음
                
                but, pasdas는 기본제공이 아닌
                import를 통한 모듈 가져와야하고
                
                pandas는 3.7 까지만해도 pip로 설치했어야했는데
                워낙 pandas가 표에 대해 강점이기때문에
                데이터분석, 가져오고 에 최적화기때문에
                중요하다.
"""

import pandas as pd

infile = "ssec1804.xls"
outfile = "ssec1804_bak.xls"

writer = pd.ExcelWriter(outfile)

df = pd.read_excel(infile, sheet_name=None, index_col=None)

for worksheet_name, data in df.items():
    print("===",worksheet_name,"===")
    print(data)
    data.to_excel(writer,sheet_name=worksheet_name,index=False,header=False)
writer.save()

2. excel _ 8

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 10:07:24 2021

@author: 2016005

excelex8.py : '폴더'에 속한 excel파일들 전부를 읽어서 
                하나의 excel파일로 합쳐 생성
                
                파이썬이 어려운 점.
                어떤 모듈을 써야하는지에 대해서.
                헷갈린다.중복되는 것도 있고.
                
                모듈을 찾는데 시간이 걸릴 것이다.
                
                회사에서는 선배들이 사용하고 있는 모듈이
                있을텐데, 그것을 여러분들이 공부를 하면서 볼것이고
                
                여기서는 파이썬이 어떤구조이며,어떤오류가 나고 어떻게 찾아가는지
                를 공부하는게 맞는것 같다
                --센세왈--
"""

import pandas as pd
import glob  # 경로명 표현시 사용되는 모듈
import os    # os : system관련 모듈- (운영체제)시스템.

inpath="C:/Users/2016005/.spyder-py3/python/workspace/20210204/excel/"
outfile = "sales_all.xlsx"

#inpath : 조회될 폴더
# *.xls*  :  inpath 폴더 내부의 파일 중 "xls"를 포함한 확장자를 가진 파일 전부
excels = glob.glob(os.path.join(inpath,"*.xls*"))
#excels는 list타입이 될 것임. 여러개니까.
print(type(excels))


rows = []
for excel in excels:
    print(excel) # 조회된 파일의 이름 (절대경로)
    #excel파일 읽기↓ 읽어서 pandas데이터로 만들었다. 시트이름지정x, 인덱스x
    dfs = pd.read_excel(excel, sheet_name=None, index_col=None)
    for sheet_name,df in dfs.items(): # 여러시트니까
        rows.append(df)
        
df_concat = pd.concat(rows, sort=False, axis=0, ignore_index=True)
writer = pd.ExcelWriter(outfile)
df_concat.to_excel(writer, sheet_name="all_data_all_worksheet", index=False)
writer.save()

3. numpy _ 1

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 10:39:20 2021

@author: 2016005

numpyex1.py : numpy 기본

수치 관련 데이터들을 쓸 수 있도록
(자바의 Math보다 훨씬 더 범위가 큼)

다차원 list를 관리하는것
그 안의 요소를 어떻게 처리하면 어떻게 쉽게 처리하는지

판다스는 표를 중심으로 데이터를 한다면

넘파이는 리스트의 데이터를 수치적으로 요소 작업하는데

데이터를 분석하거나 할때 

판다스/ 넘파이 모듈을 많이 쓰고 있다.

넘버파이썬numpy

"""
## 넘파이에서는 리스트가 아니고 이름이 배열이다.
import numpy as np

#np.arange(15) : 0 ~ 14까지 순차적인 숫자
#reshape(3,5) : 3행 5열의 배열로 설정해

a = np.arange(15).reshape(3,5) #0~14까지의 숫자를 3행5열로 배열.
print(a)
print(a.shape)  #(3,5)=>배열의 구조. 
print(a.ndim)   #배열의 차수가 몇 차원? 2차원
print(a.dtype.name) #a배열 내 요소의 자료형 (int 32비트 / 자바에서는 인트와 롱 정도라고 생각)
print(a.itemsize)  # 4  : 요소의 바이트 단위
print(a.size)    # a배열 요소 개수 전달
print(type(a))   #<class 'numpy.ndarray'> : 배열이다. 리스트와의 차이가 좀 있다.

# np.array([리스트]) : 배열을 생성해줌
b = np.array([6,7,8])
print(b)
print(type(b))

print(b.dtype)

c= np.array([1.2, 3.5, 5.1])
##c배열의 요소 자료형 출력하기
print(c.dtype)  #float64 : 자바로는 double임.

print()
#넘파이 만드는 것 . 1)리스트로써, 2)숫자형태로써, 

##튜플로도 배열 만들 수 있다.↓
d = np.array([(1.5, 2, 3), (4,5,6)])
print(d)
print(d.dtype)  # 어느 하나라도 실수면 전체자료형이 float64다.

print()
##리스트를 이용해서 배열 생성↓
e = np.array([[1,2],[3,4]], dtype=complex) 
# => dtype=complex  : 128비트의 큰 값을 저장할 수 있는 자료형이 된다.★
print(e)
print(e.dtype)

print()

#zeros
#3행 4열 2차원 배열을 생성하고 0으로 초기화. float64(실수)값으로 저장됨.
f = np.zeros((3,4))
print(f)
print(f.dtype)

print()
#ones
#3차원배열(3행4열짜리배열이2개 있는). 요소를 1로 초기화
g = np.ones((2,3,4), dtype=np.int16) #정수형으로.int16=>short형태
print(g)
print(g.dtype)

print()
#왜 자료형을 선택하느냐? float64는 8바이트. int16은 2바이트. 요소의 크기를 생각할 필요가 있으므로.

#문제 : arange함수를 이용해서 10부터 29까지의 수 중5의 배수로만 이뤄진 배열 생성
h = np.arange(10,30,5)
print(h)
print(h.dtype)

#arange(s,e,d) : s ~ e '앞' 까지 d만큼씩 증가한 수들의 목록
i = np.arange(0, 2, 0.3) #간격 지정. (start, stop, step)
print(i)
print(i.dtype)

#linspace(s,e,d) : s부터 e포함까지의 수를 d등분(균등).
j = np.linspace(0,2,9) # 0~2까지 수를 균등하게 d등분한 숫자목록
print(j)
print(j.dtype)

######
print(np.pi)  # 원주율
#0 ~ 2pi까지의 수를 100개로 
k = np.linspace(0,2*np.pi,100)
print(k)
print(k.dtype)

##
print(np.arange(10000)) # 0~10000
#[   0    1    2 ... 9997 9998 9999] 넘파이에서는 축약 출력기능도 있다.

print()
# 0 ~ 9999 까지의 수를 100행 100열 배열 생성 출력
l = np.arange(10000).reshape(100,100)
print(l)
print(l.dtype)


'''
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
(3, 5)
2
int32
4
15
<class 'numpy.ndarray'>
[6 7 8]
<class 'numpy.ndarray'>
'''

4. numpy _ 2

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 11:40:55 2021

@author: 2016005

numpyex2.py : numpy의 기본적인 연산
"""

import numpy as np

# 1차원,
a = np.array([20,30,40,50])
b = np.arange(4)  # [0, 1, 2, 3] 

print(a-b)  # 인덱스 맞춰서 지가 알아서 빼줌.
#[20 29 38 47]
#[20-0, 30-1, 40-2, 50-3]  [a-b, a-b, a-b, a-b]

print(b**2) #각각 요소에 제곱도 가능

print(a < 35) #각각 요소에 대한 boolean도 가능 [True True False False]

'''
행렬. 
빅데이터 분석쪽으로 가면 수학적으로
행렬로 들어간다. 머리아프다.
넘파이가 처리해준다.

이제 행렬식으로 들어간다.
'''

'''
[[1 1]  ? [[2 0]  => [[c?d c?d]
 [0 1]] ?  [3 4]] =>  [c?d c?d]]
'''
c = np.array([[1,1], [0,1]])
d = np.array([[2,0], [3,4]])
print(c+d) # 행렬 합
print(c*d) # 행렬 곱

print(c@d) # @ :행렬식 곱★ ::::선형대수/분석 에서 중요한 내용::::
'''
'행렬곱'과 '행렬식의곱'은 다르다.
[[1 1]    [[2 0]  => [[1*2+1*3, 1*0+1*4]
 [0 1]] @  [3 4]] =>  [0*2+1*3, 0*0+1*4]]
'''
print(c.dot(d)) # n.dot(n)행렬식 곱 : @와 같은 기능.

print()
e = np.ones((2,3), dtype=int)
print(e)
e *= 3  # e배열의 각 요소에다가 *3 해줌.
print(e)


###########서로 다른 자료형들의 연산##########
f = np.ones(3, dtype=np.int32) #int32
g = np.linspace(0,np.pi, 3) #float64
print(f.dtype, g.dtype)

h = f + g
print(h)
print(h.dtype) # => float64

#넘파이는 허수라는 것도 있는데, 그냥 하지말자.

5. numpy _ 3

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 12:06:02 2021

@author: 2016005

numpyex3.py : numpy 함수
"""

import numpy as np

a = np.arange(12).reshape(3,4)

print(a)

print(a.sum(axis=0)) #.sum(axis=0) : 열 합산
print(a.sum(axis=1)) #.sum(axis=1) : 행 합산

print(a.max(axis=0)) #.max(axis=0) : 열 기준 최대값

print(a.min(axis=1)) #.min(axis=1) : 행 기준 최소값

print(a.cumsum(axis=1)) #.cumsum(axis=1) : 행 기준 '누적'합산(모양안바꿈. 값만 바꿈)


print()
#####
b = np.arange(3)  #[0 1 2]
print(b)
print(np.exp(b))  #로그값
print(np.sqrt(b)) #제곱 근


print()
#####
c = np.array([2, -1, 4])
print(c)
print(b+c)
print(np.add(b,c)) # add함수 사용: +와 같은기능


print()
#평균 0, 표준편차 1인 정규 분포를 따르는 3행3열 난수 배열 생성
d = np.random.normal(0, 1, (3,3))  #업무에서 어떤 규격을 정해서 난수를 만들고 싶을 때 사용되는 부분이다. 
print(d)

print()
# 0 ~ 10 구간의 임의의 정수를 가진 3행 3열 배열 생성
e = np.random.randint(0, 10, (3,3))
print(e)

6. numpy _ 4

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 13:48:41 2021

@author: 2016005

numpyex4.py :
    
"""

import numpy as np
## 1차원배열
x = np.arange(10)
print(x)
print(x[:5]) # 0 ~ 4 인덱스까지 부분 배열
print(x[5:]) # 인덱스5부터 끝까지
print(x[4:7]) # 4 ~ 7인덱스바로앞 까지
print(x[::2]) # 0 ~ 끝까지 1,3,5,7,9번인덱스(2씩증가) 
print(x[1::2]) # 1인덱스부터 끝까지.2씩증가
print(x[1:8:3]) # 1 ~ 7, 3씩
print(x[::-1]) # 끝부터 0까지 역순으로 한칸씩

print()
'''
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4]
[5 6 7 8 9]
[4 5 6]
[0 2 4 6 8]
[1 3 5 7 9]
[1 4 7]
[9 8 7 6 5 4 3 2 1 0]
'''

## 2차원배열
print("0부터 9까지의 난수를 4행 5열 배열로 생성")
x = np.random.randint(0, 10, (4,5)) # 똑같은 변수를 써도 된다. 그냥 자료형이 알아서 바뀜.(그래서 나중에 어려우니, 변수이름을 미리 정해놓고 한다. 그래서 프로젝트 할때 메크로에 등록을 해야만 승인을 받아서 쓸 수 있다. 사전처리하는 부분이 꽤 있다 (파이썬의 경우), 자바는 이 변수는 이런형으로만 쓸거야 라고 해놓지. 형변환도 상당히 제약적으로 한다. 그래서 이 변수는 자료형이 고정돼서 쓸 수 있는 범위가 한정되지만, 파이썬은 그 변수를 자료형을 값에 따라 바뀌기 때문에 어느순간에 2차원배열로 됐는지를 잘 봐야하는 것이다. 어쨋든 파이선은 기능이 좋기때문에 사용하기가 편할것이다. 이러한 기능들을 익숙하게 할 필요가 있다.)
x = np.random.randint(10, size=(4,5)) # 0~9까지 난수를 위와 같이 하는데, size안쓰면 오류.
print(x)

#2차원배열에서 부분배열 가져오기
# 2개의 행과 3개의 열을 가진 부분배열을 출력해보기
print(x[:2,:3]) #행은 위에서 두개를 가져오고, 열은 2개 행에서 3개만 가져옴.

#행은 모두, 열은 한칸씩 건너서 조회
print(x[:,::2])

# 행과 열 모두 완전히 역으로 조회하기
print(x[::-1,::-1])

# 모든 행의 열만 역으로 조회하기
print(x[::,::-1])

7. numpy _ 5

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 14:10:32 2021

@author: 2016005

numpyex5.py : 배열 사본 생성, 재구조화 예제
"""

import numpy as np

#배열 요소 '참조' = [:]
x = np.random.randint(10, size=10) # 0~9까지 임의의 수 10개, 1차원배열
x_sub = x[:2]  # 참조를 하고있다. 
print(x)
print(x_sub)

x_sub[0] = 20  # 부분배열을 변경하면 원본도 변경됨. 주의★
print(x)
print(x_sub)


# 배열 '복사'    .copy
x_cop = x.copy() #넘파이에서 제공되는 배열이기때문에 여기서 제공되는 함수가 있다.
x_cop[0] = 100 # '복사'를 하게되면 원본이 바뀌지 않음.
print(x)
print(x_cop)



# 배열 재편성. 1차원배열->2차원배열로   .reshape(n,n)
x2 = x.reshape(5,2)  # 1차원배열->2차원배열로 재편성가능 reshape(n,n)
print(x2)


# 0부터 99까지의 임의의 수를 9개 가진 배열 a 생성.
# a 배열을 3행 3열로 재편성한 배열 b 생성하기
a = np.random.randint(100,size=9)
b = a.reshape(3,3)
print(a)
print(b)
###★**재편성시 주의할 점**★: 재편성될 배열의 요소 개수가 원본 배열요소 개수와 같아야함.
###    3x3 으로 하려면 9개여야함. 10개면 안됨.

8. numpy _ 6

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 14:43:08 2021

@author: 2016005

numpyex6.py : 배열의 분할과 연결
"""

import numpy as np

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[3,2,1],[6,5,4]])
print(x)
print(y)


print("1)")
#배열 연결. 붙이기.
print(np.concatenate([x,y],axis=0)) #수직기준(행이 늘어남) == vstack
print()
print(np.concatenate([x,y],axis=1)) #수평기준(열이 늘어남) == hstack
'''
[[1 2 3]
 [4 5 6]]
[[3 2 1]
 [6 5 4]]

[[1 2 3]
 [4 5 6]
 [3 2 1]
 [6 5 4]]

[[1 2 3 3 2 1]
 [4 5 6 6 5 4]]
'''
print("2)")
#그렇다면 형태가 다른 배열은 어떻게 연결?
#reshape은 개수가 맞아야 하는데, 요수개수가 다르고 형태가 다르면 어떻게 함?↓


## 형태가 다른 배열의 연결★ vstack hstack  (내부적으로 concatenate를 호출함)
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[3,2,1],[6,5,4],[3,2,1]])
z = np.array([[7],[10]])
print(x)
print(y)
print(z)
                        #★
print(np.vstack([x,y])) # vstack([n,n]) : 수직으로 연결. 행 기준 연결(열 개수가 동일해야함)
print(np.hstack([x,z])) # hstack([n,n]) : 수평으로 연결. 열 기준 연결(행 개수가 동일해야함)

#print(np.hstack([x,y])) # 오류 : 행 개수다름
#print(np.vstack([x,z])) # 오류 : 열 개수 다름


print("3)")
### 배열 분리   (상하두동강vsplit, 좌우두동강hsplit)
x = np.arange(16).reshape((4,4))
print(x)
upper, lower = np.vsplit(x,[2]) # split했으니 받을것도 여러개 변수필요. 수직[2]인덱스부터(2행기준=> 0~1행, 2~3행) 수직으로 분리된다
#                 vsplit(무엇을, [몇행부터])분리
print(upper)
print(lower)

print("4)")
# 2열 기준 분리
left, right = np.hsplit(x,[2]) #2열 분리
print(left)
print(right)

9. graph _ 1

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 15:08:31 2021

@author: 2016005

graphex1.py : 그래프 그리기
"""

import matplotlib.pyplot as plt # pip install ggplot

plt.style.use("ggplot") ##내가 이제부터 이것을 사용할거야.

subjects = ["Java","JSP","SPRING","HADOOP","PYTHON"] #막대그래프의 x좌표의 라벨
print(range(len(subjects))) # (0~4)의 값을 가지고 있다.
subjects_index = range(len(subjects)) # => 0~4까지의 값을 가지는 배열변수(range로 인해)
print(type(subjects))

scores = [65,90,85,60,95] # 막대그래프에 표현할 값들

###여기서부터 그래프 그리기. 출력.
fig = plt.figure()  # 그래프를 그릴 공간 (도화지)

ax1 = fig.add_subplot(1,1,1) #도화지의 영역 분리 -> 하나의 도화지에 여러개의 그림을 그리기위해
# (1,1,1) => 1행 1열로 1번째의 그림(사실 분리하지 않은것임)
# ax1 : 그래프 그려질 영역

ax1.bar(subjects_index, scores, align="center", color="darkblue")
# .bar() : 막대그래프로 설정.
#  (subjects_index, ~~~) : x좌표 내용의 인덱스(데이터의 개수도 됨 기준점.막대 개수)
#  (~,scores,~~~) : 막대그래프로 표현할 데이터 값
#  (align="center",color="~~~") : 정렬, 색깔

###축에 대한 내용들↓
ax1.xaxis.set_ticks_position("bottom") 
# xaxis : x축. position("bottom")
ax1.yaxis.set_ticks_position("left")
# yaxis : y축 위치.

plt.xticks(subjects_index, subjects, rotation=0, fontsize="small")
# xticks : x축설정 : (인덱스, x축들 이름, rotation=0 x축이름들은가로로, fontsize="small")

plt.xlabel("Subject") # xlabel : x축 제목
plt.ylabel("score") # ylabel : y축 제목

plt.title("class Score") # 테이블 제목

#### 메모리에 저장된 내용들을 파일로 생성시킴↓
plt.savefig("bar_plot.png", dpi=400, bbox_inches="tight")
#          ( 출력파일 이름,  해상도,   그래프가 딱 맞게)

plt.show()  # 메모리에 있는 그래프 이미지를 화면에 띄우기

10. graph _ 2

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 16:08:30 2021

@author: 2016005

graphex2.py : 그래프 여러개 작성하기

"""

import matplotlib.pyplot as plt
import numpy as np

fig, ax_lst = plt.subplots(2, 2, figsize=(8,5))
# subplots(nrows, ncols, fig_kw,...) : 2행 2열 분리.
# ax_lst : 이미지 목록
# fig : 분리된 도화지

fig.suptitle('figure sample plots') # 그래프 제목

#0행 0열의 그래프 영역
ax_lst[0][0].plot([1,2,3,4]) # plot : 가장 간단한 점 연결 선그래프 plot([데이터])
#np.random.randn: 정규분포에 맞도록 난수 발생
ax_lst[0][1].plot(np.random.randn(4,10), np.random.randn(4,10))
####print(np.random.randn(4,10))  :  난수 점들이 많이 생김.

ax_lst[1][0].plot(np.linspace(0.0, 5.0), np.cos(2*np.pi*np.linspace(0.0 ,5.0)))

ax_lst[1][1].plot([3,7],[5,4])

plt.show()

11. graph _ 3

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 16:10:48 2021

@author: 2016005

graphex3.py : pandas 데이터를 이용하여 그래프 그리기

판다스 자체에서도 그래프를 그려줄 수 있다.
판다스에서 큰 데이터들을 가져와서
그래프를 그려줄 수 있는 것이 존재하고있다.
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.style.use("ggplot")

fig, axes = plt.subplots(nrows=1, ncols=2) # 1행 2열
#                        (1,2)와 같음. 그림영역을 분리
# fig는 이미지?
# axes는 그래프?


ax1, ax2 = axes.ravel()  # ravel() 로 두개로 나눠준 것.

data_frame = pd.DataFrame(np.random.rand(5,3), 
    index= ["Customer 1", "Customer 2", "Customer 3", "Customer 4", "Customer 5"],
   columns = pd.Index(["Matric 1", "Matric 2", "Matric 3"],
    name="Metrics"))
# pandas의 이름이 Metrics야
# np.random.rand(5,3) : 5행 3열짜리 난수 발생 (0<= x <1.0) * 15개
'''
Metrics     Matric 1  Matric 2  Matric 3
Customer 1  0.038908  0.055976  0.893529
Customer 2  0.172594  0.928720  0.651430
Customer 3  0.872151  0.590045  0.682208
Customer 4  0.025378  0.198247  0.129191
Customer 5  0.023164  0.792074  0.161822
'''
print(data_frame)

data_frame.plot(kind="bar", ax=ax1, alpha=0.75, title="Bar plot")
#data_frame데이터로 bar그래프로 작성할 것이다. 
# 형태지정 : kind="bar"
# 영역지정 : ax = ax1
# 알파필터 : alpha=0.75 투명정도
# 제목지정 : title=""

### x, y축 설정
plt.setp(ax1.get_xticklabels(), rotation=45, fontsize=10)
#rotation=45 : 45도 틀어
plt.setp(ax1.get_yticklabels(), rotation=0, fontsize=10)
#rotation=0 : 똑바르게

ax1.set_xlabel("Customer") #x축이름설정
ax1.set_ylabel("Value") #y출이름 설정
ax1.xaxis.set_ticks_position("bottom")
ax1.yaxis.set_ticks_position("left")

#dict() : dictionary 데이터 설정
colors = dict(boxes="DarkBlue",\
              whiskers="Gray", medians="Red", caps="Black")

   ###
data_frame.plot(kind="box", color=colors, sym="r.", ax=ax2, title="Box plot")
# box형 그래프


plt.setp(ax2.get_xticklabels(), rotation=45, fontsize=10)
plt.setp(ax2.get_yticklabels(), rotation=0, fontsize=10)
ax2.set_xlabel("Metric")
ax2.set_ylabel("Value")
ax2.xaxis.set_ticks_position("bottom")
ax2.yaxis.set_ticks_position("left")


12. graph _ 4

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 15:08:31 2021

@author: 2016005

graphex4.py : 그래프 그리기==> graphex1.py를 한글로 바꿈
"""

import matplotlib.pyplot as plt # pip install ggplot



################################################
#한글 처리를 위한 설정★★★★★
from matplotlib import font_manager, rc  #font_manager와 rc모듈

font_name = font_manager.FontProperties(fname="c:/windows/fonts/malgun.ttf").get_name() 
#주의할점 : 내 시스템 중 폰트설정 시 한글처리가능한 폰트로 지정할 것. #맑은고딕.
rc('font', family=font_name)
# 현재 폰트를 변경 설정 : font_name으로.

################################################






plt.style.use("ggplot") ##내가 이제부터 이것을 사용할거야.

subjects = ["자바","JSP","스프링","하둡","파이썬"] #막대그래프의 x좌표의 라벨
print(range(len(subjects))) # (0~4)의 값을 가지고 있다.
subjects_index = range(len(subjects)) # => 0~4까지의 값을 가지는 배열변수(range로 인해)
print(type(subjects))

scores = [65,90,85,60,95] # 막대그래프에 표현할 값들

###여기서부터 그래프 그리기. 출력.
fig = plt.figure()  # 그래프를 그릴 공간 (도화지)

ax1 = fig.add_subplot(1,1,1) #도화지의 영역 분리 -> 하나의 도화지에 여러개의 그림을 그리기위해
# (1,1,1) => 1행 1열로 1번째의 그림(사실 분리하지 않은것임)
# ax1 : 그래프 그려질 영역

ax1.bar(subjects_index, scores, align="center", color="darkblue")
# .bar() : 막대그래프로 설정.
#  (subjects_index, ~~~) : x좌표 내용의 인덱스(데이터의 개수도 됨 기준점.막대 개수)
#  (~,scores,~~~) : 막대그래프로 표현할 데이터 값
#  (align="center",color="~~~") : 정렬, 색깔

###축에 대한 내용들↓
ax1.xaxis.set_ticks_position("bottom") 
# xaxis : x축. position("bottom")
ax1.yaxis.set_ticks_position("left")
# yaxis : y축 위치.

plt.xticks(subjects_index, subjects, rotation=0, fontsize="small")
# xticks : x축설정 : (인덱스, x축들 이름, rotation=0 x축이름들은가로로, fontsize="small")

plt.xlabel("과목") # xlabel : x축 제목
plt.ylabel("점수") # ylabel : y축 제목

plt.title("과정 점수") # 테이블 제목

#### 메모리에 저장된 내용들을 파일로 생성시킴↓
plt.savefig("bar_plot.png", dpi=400, bbox_inches="tight")
#          ( 출력파일 이름,  해상도,   그래프가 딱 맞게)

plt.show()  # 메모리에 있는 그래프 이미지를 화면에 띄우기

==========exam=======

1. exam _ 1

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 13:35:37 2021

@author: 2016005

exam1.py : 
    
    
"""
import numpy as np

print("\n 0부터 9까지 정수 10개의 요소를 0으로 채운 배열 생성")
print(np.zeros(10, dtype=int))

print("\n 3행 5열의 요소를 1으로 채운 배열 생성")
print(np.ones((3,5)))

print("\n 0~20 까지의 수를 2씩 증가시킨 값을 배열 생성")
print(np.arange(0,20+1,2))

print("\n 0과 1사이의 일정한 간격의 5개의 값을 가진 배열 생성")
print(np.linspace(0,1,5))


####
print("3행 5열, 값이 전부 3.14인 배열(초기화시키는 함수)")
arr = np.full((3,5), 3.14)
print(arr)

'''

배열이므로 첨자로 접근할 수 있다.


'''

 

==========test========

1. test _ 1

# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 17:05:29 2021

@author: 2016005

1. sales_2015.xlsx 파일을 읽어서 1월의 고객별 판매금액을 막대그래프로 출력하기
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


infile = "C:/Users/2016005/.spyder-py3/python/workspace/20210204/excel/sales_2015.xlsx"

sales_2015 = pd.read_excel(infile, sheet_name="january_2015",index_col=None)

print(sales_2015)

cus = sales_2015["Customer Name"]
sa = sales_2015["Sale Amount"]
index = range(len(cus))

fig = plt.figure()

graph1 = fig.add_subplot(1,1,1)
graph1.bar(index,sa, align="center", color="blue")

graph1.xaxis.set_ticks_position("bottom")
graph1.yaxis.set_ticks_position("left")

plt.xticks(index, cus, rotation=0, fontsize="small")
plt.xlabel("고객명")
plt.ylabel("판매금액")
plt.title("2015-01 고객별 판매금액")

plt.show()


################선생님 방법↓###########################
df = pd.read_excel(infile, "january_2015", index_col=None)
df_value = df.loc[:,["Customer Name", "Sale Amount"]]
plt.style.use("ggplot")

customers = list(df_value["Customer Name"])  # x축이 됨

#print(customers)

customers_index = range(len(customers))

amounts = list(df_value["Sale Amount"])

#그래프 출력설정
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
#막대그래프 설정
#           인덱스         데이터
ax1.bar(customers_index, amounts, align="center", color="darkblue")
ax1.xaxis.set_ticks_position("bottom")
ax1.yaxis.set_ticks_position("left")
#x축의 이름들을 설정
plt.xticks(customers_index,customers, rotation=0, fontsize="small")
plt.xlabel("customer")
plt.ylabel("amount")
plt.title("sales amount")
#plt.savefig("sales_amount1.png",dpi=400,bbox_inches="tight")
plt.show()
반응형

'공부중 > python' 카테고리의 다른 글

파이썬 입문 6일차  (0) 2021.02.18
파이썬 입문 5일차  (0) 2021.02.15
파이썬 입문 3일차  (0) 2021.02.08
파이썬 입문 2일차  (0) 2021.02.08
파이썬 입문 1일차  (0) 2021.02.08