728x90
반응형
1. 행(index) 추가하기
2. 정렬하기
3. seaborn. titanic (조회, 정렬)
4. seaborn. mpg. (상관계수, 시각화[산점도, 히스토그램], 전체행렬)
5. 시도별 전출입 인구수 분석하기 (결측값 처리)
6. matplot : 기본 시각화모듈
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 21 09:34:54 2022
@author: p011v
"""
'''
pandas 모듈
- 표형태(행:index,열:columns)의 데이터를 처리하기 위한 모듈
- Series : 1차원형태의 데이터처리.DataFrame의 한개의 컬럼값들의 자료형
- DataFrame : 표형태의 데이터. Series데이터의 모임.
- 기술통계함수 : sum, mean, median, max, min, std, var,...
- 행의 값 : index
- 열의 값 : columns
- rename : index, columns의 값을 변경하는 함수
- drop : index, columns의 값을 제거하는
- 얕은복사 : df2 = df
- 깊은복사 : df3 = df[:], df4 = df.copy()
- 한개의 컬럼조회 : df["컬럼명"], df.컬럼명 => Series 객체
- 여러개의 컬럼조회 : df[["컬럼1","컬럼2"]] => DataFrame 객체
df["컬럼1":"컬럼n"] => DataFrame 객체. 범위지정
- 행을 조회 : loc["인덱스명"], iloc[인덱스순서]
- csv 파일 읽기 : read_csv
- csv 파일 쓰기 : to_csv
- excel 파일 읽기 : read_excel
- excel 파일 쓰기 : ExcelWriter > to_excel > save
ex)df500데이터를 pd_sale_2015.xlsx파일의 jan_2015_500 sheet로 저장하기
1. outexcel = pd.ExcelWriter("data/pd_sale_2015.xlsx") #내용없는 엑셀파일 생성
#to_excel(엑셀파일, sheet명, 인덱스여부)
2. df500.to_excel(outexcel, sheet_name="jan_2015_500", index=False) #엑셀에 data 추가
3. outexcel.save() #저장하기. 엑셀파일로 생성
'''
########## 1. 행(index) 추가하기
import pandas as pd
dict_data = {'c0':[1,2,3], 'c1':[4,5,6], 'c2':[7,8,9], 'c3':[10,11,12], 'c4':[13,14,15]}
df=pd.DataFrame(dict_data, index=['r0','r1','r2'] )
df
df.index=['r0','r1','r2','r3','r4'] #인덱스의 갯수와 행의 갯수는 동일해야함
# reindex() : 인덱스를 5개로 재설정. 행이 추가됨
# Nan : 결측값 (값이 없다.)
ndf = df.reindex(['r0','r1','r2','r3','r4'])
ndf
# fill_value : 추가된 행에 0으로 추가
ndf2 = df.reindex(['r0','r1','r2','r3','r4'], fill_value = 0)
ndf2
########## 2. 정렬하기
# sort_index() : 인덱스이름으로 정렬
# 인덱스 기준으로 내림차순 정렬하기
# ascending=False : 내림차순 정렬 방식
print(df.sort_index()) #인덱스 기준 오름차순 정렬방식
print(df.sort_index(ascending=False)) #인덱스 기준 내림차순 정렬방식
print(ndf2.sort_index(ascending=False))
# sort_values() : 기준컬럼을 설정하여 해당 컬럼값을 기준으로 정렬
print(df.sort_values(by="c1", ascending=False))
exam_data={"이름":["서준","우현","인아"],
"수학":[90,80,70],
"영어":[98,89,98],
"음악":[85,95,100],
"체육":[100,90,90]}
df = pd.DataFrame(exam_data)
df
#이름컬럼을 인덱스로 변경하기
df.set_index("이름", inplace=True)
df
#이름의 역순으로 출력하기
df.sort_index(ascending=False) #인덱스 기준 내림차순 정렬방식
df
# inplace=True : 객체를 역순으로 변경
df.sort_index(ascending=False, inplace=True)
df
#영어점수 순으로 출력하기
df.sort_values(by="영어")
df.sort_values(by="영어", ascending=True)
df
#영어점수 내림차순으로 출력하기
df.sort_values(by="영어", ascending=False)
#df객체를 역순으로 변경하기 : inplace=True
df.sort_values(by="영어", inplace=True)
df
########## 3. seaborn. titanic (조회, 정렬)
# titanic 데이터셋 연습하기
# seaborn 모듈에 저장된 데이터 이용하기 (데이터내부에 titanic 존재함)
import pandas as pd
import seaborn as sns #pip install seaborn
#seaborn 모듈이 가지고 있는 데이터셋 목록
print(sns.get_dataset_names())
# titanic 데이터 로드. 다운을 받고, DataFrame객체로 로드
titanic = sns.load_dataset("titanic")
titanic
type(titanic)
# 앞쪽 5개 레코드만 조회
titanic.head() #처음 5개행만 조회
# 마지막 5개 레코드만 조회
titanic.tail() #마지막 5개행만 조회
# 전체적인 구조 조회
titanic.info() #Dtype => category : 범위타입
# adult_male 컬럼의 값 5개만 조회하기
titanic["adult_male"].head() #처음 5개행만 조회
'''
survived: 생존여부
pclass: 좌석등급 (숫자)
sex: 성별
age: 나이
sibsp: 형제자매 + 배우자 인원수
parch: 부모 + 자식 인원수
fare: 요금
embarked: 탑승 항구
class: 좌석등급 (영문)
who: 성별
adult_male: 성인남자여부
deck: 선실 고유 번호 가장 앞자리 알파벳
embark_town: 탑승 항구 (영문)
alive: 생존여부 (영문)
alone: 혼자인지 여부
'''
#pclass, class 컬럼 5개만 조회하기
titanic[["pclass", "class"]].head() #처음 5개행만 조회
#컬럼명만 조회하기
titanic.columns
#titanic의 age, fare 컬럼만을 df 데이터셋에 저장하기
df = titanic[["age", "fare"]]
df.info()
#df 데이터의 레코드 건수
df.count() #결측값은 건수에서 제외
#df 데이터의 age컬럼의 레코드 건수
df.age.count() #결측값은 건수에서 제외
df["age"].count()
df.count()["age"]
'''
빅데이터 특징
3V
1. Volume : 량. 데이터의 양이 대용량.
2. Velocity : 속도. 데이터의 처리속도가 빨라야 한다.
3. Variety : 다양성. 데이터 형태의 다양성
정형데이터 : dbms (형태가 정해져있는 데이터)
반정형데이터 : Json, xml, Html (형태를 만들수 있는 데이터)
비정형데이터 : 이미지, 음성
'''
#df 데이터의 평균데이터 조회
df.mean()
#df 데이터 나이의 평균데이터 조회하기
df.mean()["age"]
df["age"].mean()
df.age.mean()
#df 데이터 나이가 가장많은, 가장적은 데이터 조회하기
print(df.age.max(), df.age.min())
#value_counts() : 나이별로 인원수 조회. 건수의 내림차순조회
#나이별로 인원수 조회
df.age.value_counts()
#나이별로 인원수 최대 5건만 조회
df.age.value_counts().head()
#나이별로 인원수 최대 10건만 조회
df.age.value_counts().head(10)
#승객중 최고령자 정보 조회하기
df[df["age"] == df["age"].max()]
titanic[titanic["age"] == titanic["age"].max()]
#생존, 사망 건수 조회
titanic["survived"].value_counts()
titanic["alive"].value_counts()
#성별로 생존 건수 조회하기
titanic[["sex", "survived"]].value_counts()
titanic[["sex", "alive"]].value_counts()
#성별 인원수 조회하기
titanic["sex"].value_counts()
########## 4. seaborn. mpg. (상관계수, 시각화[산점도, 히스토그램], 전체행렬)
'''
mpg : 연비
cylinders : 실린더 수
displacement : 배기량
horsepower : 출력
weight : 차량무게
acceleration : 가속능력
model_year : 출시년도
origin : 제조국
name : 모델명
'''
import pandas as pd
import seaborn as sns #pip install seaborn
mpg = sns.load_dataset("mpg")
mpg.head()
mpg.info()
#제조국별 자동차 건수 조회
mpg.origin.value_counts()
#origin 컬럼의 값을 조회하기
list(mpg.origin.unique())
#mpg 데이터의 통계정보 조회하기
mpg.describe() #기술통계정보를 처리하였을때 숫자형태의 컬럼들만 조회
mpg.describe(include="all") #기술통계정보를 처리하였을때 모든 컬럼들 조회
#mpg 데이터의 행, 열의 갯수 조회하기
mpg.shape #튜플데이터로 조회
#행의 수 조회
mpg.shape[0]
#열의 수 조회
mpg.shape[1]
#모든 컬럼의 자료형 조회하기
mpg.dtypes
#mpg 컬럼의 자료형 조회하기
mpg["mpg"].dtypes
mpg.mpg.dtypes
# mpg데이터의 mpg, weight 컬럼의 최대값 조회하기
mpg[["mpg", "weight"]].max()
# mpg데이터의 mpg, weight 컬럼의 기술통계정보 조회하기
mpg[["mpg", "weight"]].describe()
# 최대 연비를 가진 자동차의 정보 조회하기
mpg[mpg["mpg"] == mpg.mpg.max()]["weight"]
#상관계수 : -1 ~ 1 사이의 값을 가짐. 컬럼간의 관계도를 수치로 표현함.
# 1 : 상관도가 완벽하게 일치. c1 1증가하면 c2 1증가.
# -1 : 상관도가 반비례. c1 1증가하면 c2 -1증가.
# 0 : 상관이 없다고 판단.
#mpg 데이터의 모든 컬럼들간의 상관계수 조회
mpg.corr()
#mpg 데이터의 mpg, weight 컬럼들간의 상관계수 조회
mpg[["mpg", "weight"]].corr()
'''
그래프 출력영역 설정
Tools > Preferences > IPython Console > Graphics 탭 선택 > Backend : Automatic 변경
'''
#DataFrame 객체를 이용하여 시각화하기.
#산점도 : 두개 컬럼의 각각 값들을 x,y축의 점으로 표현하기.
# 값의 분표. 컬럼사이의 관계를 시각화
mpg.plot(x="mpg", y="weight", kind="scatter")
#히스토그램 : 데이터의 빈도수를 그래프화함. 데이터의 분포를 시각화.
#mpg 데이터의 mpg 컬럼의 히스토그램 시각화
mpg.mpg.plot(kind="hist")
# 남북한발전전력량.xlsx 파일을 읽어서 df에 저장하기
df = pd.read_excel("data/남북한발전전력량.xlsx")
df
# 0행, 5행 데이터의 2열 이후의 정보만 ndf 데이터 저장하기
# 0행, 5행 데이터정보만 ndf 데이터 저장하기
ndf = df.iloc[[0, 5]]
ndf
# 2열 이후의 정보만 ndf 데이터 저장하기
# iloc[행의시작:행의종료, 열의시작:열의종료] => 순서번호로 구분
ndf = df.iloc[[0,5], 2:]
ndf.info()
# 선그래프로 출력하기. 컬럼별로 그래프 작성.년도별로 그래프.
ndf.plot()
# 남한, 북한별로 그래프 작성하기
# 전치행렬 : 행과 열을 바꿔야 함.
ndf2 = ndf.T
ndf2
# ndf2 데이터의 컬럼명을 변경하기
ndf2.columns=["South", "North"]
ndf2
ndf2.info()
ndf2.plot() #선그래프
ndf.plot(kind="bar")#막대그래프
# 데이터값이 숫자형으로 변환
ndf2.astype(int)
ndf.plot(kind="hist")#히스토그램
########## 5. 시도별 전출입 인구수 분석하기 (결측값 처리)
#1. excel 파일 읽기
import pandas as pd
df = pd.read_excel("data/시도별 전출입 인구수.xlsx")
df.info()
df.head()
#2. 결측값 처리 : 앞데이터로 채움
#fillna : 결측값을 다른값으로 변경하는 함수
df = df.fillna(method="ffill") #앞의 데이터로 결측값 채움
df.head()
df.info()
#3. 전출지가 서울에서 다른 지역으로 이동한 데이터만 추출하기
#전출지는 서울이고, 전입지는 서울이 아닌 데이터만 추출하기
mask = (df["전출지별"] == '서울특별시') & (df["전입지별"] != '서울특별시')
mask
#mask의 값이 true/false인 데이터의 갯수 출력하기
mask.value_counts()
df_seoul = df[mask]
df_seoul
#4. 컬럼명을 전입지별 => 전입지 변경하기
df_seoul.rename(columns={"전입지별":"전입지"}, inplace=True)
df_seoul.head()
#5. 전출지별 컬럼을 제거
df_seoul = df_seoul.drop("전출지별", axis=1)
df_seoul.head()
#6. 전입지 컬럼을 인덱스로 설정하기
df_seoul.set_index("전입지", inplace=True)
df_seoul.head()
#7. 경기도로 이동한 데이터만 sr1 변수에 저장하기
sr1 = df_seoul.loc["경기도"]
sr1
sr1.index
#8. sr1 시작화하기
########## 6. matplot : 기본 시각화모듈
import matplotlib.pyplot as plt
#한글이 가능한 폰트로 설정 : 맑은 고딕
plt.rc("font", family="Malgun Gothic") #한글처리를 위한 폰트 설정
plt.plot(sr1)
plt.title("서울=>경기 이동 인구")
plt.xlabel("년도")
plt.ylabel("이동인구수")
plt.xticks(rotation = "vertical") #x축의 값을 세로로 설정
#사용가능한 스타일 목록
plt.style.available
plt.style.use("ggplot") #스타일 설정
plt.figure(figsize=(14,5)) #그래프작성 창의 크기 지정
plt.xticks(rotation="vertical", size=10) #x축의 값을 세로로 설정. 글자크기 : 10
plt.plot(sr1, marker='o', markersize=10)
plt.title("서울=>경기 이동 인구")
plt.xlabel("년도")
plt.ylabel("이동인구수")
plt.legend(label=["서울->경기"], loc="best") #범례. 범례위치 가장 적당한 곳
728x90
반응형
'study > Python' 카테고리의 다른 글
[Python] 36. Test 답 (0) | 2022.06.21 |
---|---|
[Python] 36. Test (0) | 2022.06.21 |
[Python] 35. Test 답 (0) | 2022.06.20 |
[Python] 35. Test (0) | 2022.06.20 |
[Python] 35. pandas(Series, DataFrame, 기술통계함수, 데이터 복사/삭제/조회/저장하기) (0) | 2022.06.20 |