반응형
DataFrame
파이썬에서 사용할 수 있는 데이터분석 라이브러리 Pandas를 사용 index,column 을 사용 2차원형태로 이루어짐.
- index
- column
import pandas as pd
import numpy as np
# list 사용하여 Dataframe 만들기
d1 = [[1,2],[3,4],[5,6]]
df1 = pd.DataFrame(d1,index=['a','b','c'],columns = ['kor','eng'])
df1
-> kor eng
a 1 2
b 3 4
c 5 6
# dictionary를 사용한 DataFrame 생성
data = {'eng':[10,30,50,70],
'kor':[20,40,60,80],
'math':[90,50,20,70]}
df = pd.DataFrame(data,index = ['a','b','c','d'])
df
->
eng kor math
a 10 20 90
b 30 40 50
c 50 60 20
d 70 80 70
속성
- ndim : 차원의 수를 화긴
- shape : 데이터프레임의 모양확인
- size : 데이터프레임의 총 개수 확인
- len() : 데이터프레임의 총 행의개수 확인
# df의 차원
df.ndim
-> 2
#df 의 모양
df.shape
-> (4, 3)
# df의 총 개수
df.size
-> 12
# df가 몇개인지 확인
len(df)
-> 4
통계 (기본 axis = 0)
- max() : 최대값 출력
- unstack() : index값을 column으로 올려줌 (stack은 column이 index로) 이 떄, series로 변환됨
- sum(): 합 출력
- mean() : 평균
- median() : 중위값
- std() : 표준편차
- var() : 분산
- quantile() : 분위수 출력
- count() : 개수를 세는 함수
- describe() : 전반적인 통계자료를 출력
- apply : 함수사용 (임시 함수 lambda 를 사용하여 간편하게 만들어 사용가능)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# font 설정 (Malgun Gothic)
import matplotlib
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
matplotlib.rcParams['axes.unicode_minus'] =False
# 자료제작
data = {'eng':[10,30,50,70],
'kor':[20,40,60,80],
'math':[90,50,20,70]}
df = pd.DataFrame(data,index=['a','b','c','d'])
df
# max함수
df.max()
->
eng 70
kor 80
math 90
dtype: int64
df.max(axis = 1)
->
a 90
b 50
c 60
d 80
dtype: int64
# unstack함수
df.unstack()
->
eng a 10
b 30
c 50
d 70
kor a 20
b 40
c 60
d 80
math a 90
b 50
c 20
d 70
dtype: int64
df.unstack().index()
->
MultiIndex([( 'eng', 'a'),
( 'eng', 'b'),
( 'eng', 'c'),
( 'eng', 'd'),
( 'kor', 'a'),
( 'kor', 'b'),
( 'kor', 'c'),
( 'kor', 'd'),
('math', 'a'),
('math', 'b'),
('math', 'c'),
('math', 'd')],
)
#sum 함수
df.sum()
->
eng 160
kor 200
math 230
dtype: int64
df.sum(axis = 1 )
->
a 120
b 120
c 130
d 220
dtype: int64
# mean 함수
df.mean()
->
eng 40.0
kor 50.0
math 57.5
dtype: float64
#median 함수
df.median()
->
eng 40.0
kor 50.0
math 60.0
dtype: float64
# std함수
df.std()
->
eng 25.819889
kor 25.819889
math 29.860788
dtype: float64
# quantile 함수
df.quantile([0.25,0.5,0.75])
->
eng kor math
0.25 25.0 35.0 42.5
0.50 40.0 50.0 60.0
0.75 55.0 65.0 75.0
# describe 함수
df.describe()
->
eng kor math
count 4.000000 4.000000 4.000000
mean 40.000000 50.000000 57.500000
std 25.819889 25.819889 29.860788
min 10.000000 20.000000 20.000000
25% 25.000000 35.000000 42.500000
50% 40.000000 50.000000 60.000000
75% 55.000000 65.000000 75.000000
max 70.000000 80.000000 90.000000
# 함수 사용 후 적용 (lambda x: 하고싶은거 (조건있으면 사용))
df.apply(lambda v: '합격' if v.mean()>=70 else '불합격', axis = 1)
->
이름
a 불합격
b 불합격
c 불합격
d 합격
dtype: object
# 시각화
# 막대그래프로 시각화 하고 y축은 eng,math만 사용, y축 범위는 0-100으로
df.plot(kind = 'bar',y =['eng','math'],ylim=(0,100))
plt.show()
반응형
'python' 카테고리의 다른 글
python series 정리 (기초) (0) | 2023.04.15 |
---|