2) usecols, userows : 엑셀에서 어느 행 혹은 어느 열을 불러올지 선택 가능.
3) names= 행의 이름
col_names= ['스트레스','스트레스남학생','스트레스여학생','우울감','우울남학생','우울여학생','자살생각률','자살남학생','자살여학생'] #컬럼 이름 정의
raw_data= pd.read_excel('C:\\Users\\ASUS\\Downloads\\Report.xls', header=1, usecols="C:K", names=col_names)
2. dataframe 데이터 정렬
새로운 행 추가 : df.loc[1]= 100- df.loc[0] (기존의 행을 참조하여 연산 결과로 df.loc[1]을 새로 추가)
새로운 열 추가 : df['@@']= ['##', '###'] (하나의 값을 넣으면 해당 열 모든 값이 하나의 값으로 중복되어 입력)
raw_data.loc[1]=100-raw_data.loc[0] # 데이터 프레임의 열을 나타낼 때, loc[i] 로 나타낼 수 있음.
raw_data['응답']=['그렇다','아니다'] # loc 없이 그냥 chr or str 형식이면 일반적으로 column을 나타냄
raw_data.set_index('응답',drop=True, inplace=True) # 인덱스를 위에서 정의한 컬럼인 '응답' 으로 지정. inplace = 기존의 인덱스 0,1,2,.. 를 이걸로 대체한다. drop = 기존 인덱스는 버린다.
* inplace=True :
raw_data=raw_data.set_index(~ 이렇게 하지 않으면, raw_data 값에 새로 인덱스 설정한 값이 저장되지 않는다.
inplace=True 는 앞에 'raw_data=' 를 붙이지 않아도 raw_data 값이 갱신되게 해준다.
특정 컬럼 지우기 : .drop(columns=' 컬럼 이름' , inplace=True)
raw_data['스트레스'].plot.pie(explode=[0,0.02]) # plot 모듈의 pie 차트 기능. explode : 다른 영역 간 간격
여러 플롯 그리는 경우
plt 모듈에서 subplots ( 행, 열, figsize=(가로, 세로))
f= figure, ax= axis 속성
그래프 제목 : ax[i]. set_title
그래프 라벨 : ax[i].ylabel
subplots 혹은 plot 으로 시작하여
plt.show() 로 끝남 둘 사이의 plot들을 모두 출력
f, ax = plt.subplots(1,3, figsize=(16,8)) # 1행 3열의 플롯을 그린다. f는 figure, ax는 axes 속성 지정
raw_data['스트레스'].plot.pie(explode = [0, 0.02], ax=ax[0], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[0].set_title('스트레스를 받은 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[0].set_ylabel('')
raw_data['우울감'].plot.pie(explode = [0, 0.02], ax=ax[1], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[1].set_title('우울증을 경험한 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[1].set_ylabel('')
raw_data['자살생각률'].plot.pie(explode = [0, 0.02], ax=ax[2], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[2].set_title('자살을 고민한 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[2].set_ylabel('')
plt.show()
[풀 코드]
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import font_manager, rc
f_path ="C:\Windows\Fonts\HYWULM.ttf" # matplotlib 에서 한글지원하도록 해주는 폰트
font_name=font_manager.FontProperties(fname=f_path).get_name()
rc('font', family=font_name)
# f. ~ 으로 나타내는 것은 print해보면 해당 값이 아닌 주소 값임을 알 수 있다.
col_names= ['스트레스','스트레스남학생','스트레스여학생','우울감','우울남학생','우울여학생','자살생각률','자살남학생','자살여학생'] #컬럼 이름 정의
raw_data= pd.read_excel('C:\\Users\\ASUS\\Downloads\\Report.xls', header=1, usecols="C:K", names=col_names ) #pandas의 read_excel을 사용해, 데이터를 데이터 프레임으로 가져옴
# 기존 엑셀의 C:K 까지의 컬럼을 가져옴. 컬럼 이름은 col_names
raw_data.loc[1]=100-raw_data.loc[0] # 데이터 프레임의 열을 나타낼 때, loc[i] 로 나타낼 수 있음.
raw_data['응답']=['그렇다','아니다'] # loc 없이 그냥 chr or str 형식이면 일반적으로 column을 나타냄
raw_data.set_index('응답',drop=True, inplace=True) # 인덱스를 위에서 정의한 컬럼인 '응답' 으로 지정. inplace = 기존의 인덱스 0,1,2,.. 를 이걸로 대체한다. drop = 기존 인덱스는 버린다.
raw_data['스트레스'].plot.pie(explode=[0,0.02]) # plot 모듈의 pie 차트 기능. explode : 다른 영역 간 간격
f, ax = plt.subplots(1,3, figsize=(16,8)) # 1행 3열의 플롯을 그린다. f는 figure, ax는 axes 속성 지정
raw_data['스트레스'].plot.pie(explode = [0, 0.02], ax=ax[0], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[0].set_title('스트레스를 받은 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[0].set_ylabel('')
raw_data['우울감'].plot.pie(explode = [0, 0.02], ax=ax[1], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[1].set_title('우울증을 경험한 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[1].set_ylabel('')
raw_data['자살생각률'].plot.pie(explode = [0, 0.02], ax=ax[2], autopct='%1.1f%%') # 데이터, 그래프 내부
ax[2].set_title('자살을 고민한 적 있다. ')# a[0]: 서브플롯 3개중 첫번째 플롯의 속성. label, axis 등 축 관련 속성
ax[2].set_ylabel('')
plt.show()