pandas 는 고수준의 자료 구조와 파이썬을 통한 빠르고 쉬운 데이터 분석 도구를 포함하고 있다.
명시적으로 축의 이름에 따라 데이터를 정렬할 수 있는 자료 구조를 제공한다.
통합된 시계열 데이터 처리 기능을 제공한다.
시계열 데이터와 비시계열 데이터를 함께 다룰 수 있는 통합 자료구조를 제공한다.
누락된 데이터를 유연하게 처리를 할 수 있다.
SQL과 같은 일반 데이터베이스처럼 데이터를 합치고 관계연산을 수행 할 수 있다.
일련의 객체를 담을 수 있는 1차원 백터
색인(index)라고하는 배열의 데이터에 연관된 이름을 가지고 있다.
series 객체의 문자열 표현은 왼쪽에 색인을 보여주고 오른쪽에 해당 색의 값을 보여준다.
import pandas as pd
import numpy as np
obj = pd.Series([4,7,-5,3])
print(obj)
print(obj.index)
print(obj.values)
print(type(obj.values))
print()
obj2 = pd.Series([4,7,-5,3], index=['a','b','c','a'])
print(obj2)
print()
print(obj2['c'])
print(obj2[['c','b']])
obj2['c'] = 100
print(obj2)
코드를 입력하세요
표 같은 스프레드시트 형식의 자료 구조로 여러 개의 칼럼이 있는데 서로 다른 종류의 값을 담을 수 있다.
DataFrame은 색인의 모양이 같은 Series 객체를 담고 있는 파이썬 사전으로 생각하면 편하다.
from operator import index
import pandas as pd
import numpy as np
np.random.seed(12345)
frame1 = pd.DataFrame([[10,20,30],[50,60,70]])
print(frame1)
print()
frame2 = pd.DataFrame([[10,20,30],[50,60,70]],
index=['one','tow'],
columns=['first','second','third'])
print(frame2)
print()
print(frame2.index)
print(frame2.columns)
ldata = [('김가',100,80),('이가',160,50),('최가',170,65),('오가',165,60)]
frame3 = pd.DataFrame(ldata, columns=['이름','키','몸무게'],
index=[11,12,21,22])
print(frame3)
ddata = {'state':['ohio','ohio','nevada','nevada'],
'year':[2020,2021,2020,2021],
'pop':[1.5,1.7,3.6,2.4]}
frame4 = pd.DataFrame(ddata)
print(frame4)
frame4 = pd.DataFrame(ddata, columns=['year','pop','state'],
index=['one','two','three','four'])
print(frame4)
# frame4 = pd.DataFrame(ddata, columns=['year','pop','info'])
# print(frame4)
print(frame4['state'])
print(type(frame4['state']))
print()
print(frame4.state)
print()
print(frame4.loc['two'])
print()
print(frame4['pop']['two'])
print(frame4.loc['two']['pop'])
print()
print(frame4.year.two)
print(frame4.loc['two'].year)
print()
print(frame4)
print()
frame4['area'] = pd.Series([32.323, 32.323, 562.43, 562.43], index=['one','two','three','four'])
# frame4['area'] = pd.Series([32.323, 32.323, 562.43, 562.43], index=frame4.index)
print(frame4)
print()
frame4.loc['five']= pd.Series([2020, 3.3,'utah','656.61'],
index=frame4.columns)
print(frame4)
print()
frame4.index.name = 'id'
frame4.columns.name = 'info'
print(frame4)
0 1 2
0 10 20 30
1 50 60 70
first second third
one 10 20 30
tow 50 60 70
Index(['one', 'tow'], dtype='object')
Index(['first', 'second', 'third'], dtype='object')
이름 키 몸무게
11 김가 100 80
12 이가 160 50
21 최가 170 65
22 오가 165 60
state year pop
0 ohio 2020 1.5
1 ohio 2021 1.7
2 nevada 2020 3.6
3 nevada 2021 2.4
year pop state
one 2020 1.5 ohio
two 2021 1.7 ohio
three 2020 3.6 nevada
four 2021 2.4 nevada
one ohio
two ohio
three nevada
four nevada
Name: state, dtype: object
<class 'pandas.core.series.Series'>
one ohio
two ohio
three nevada
four nevada
Name: state, dtype: object
year 2021
pop 1.7
state ohio
Name: two, dtype: object
1.7
1.7
2021
2021
year pop state
one 2020 1.5 ohio
two 2021 1.7 ohio
three 2020 3.6 nevada
four 2021 2.4 nevada
year pop state area
one 2020 1.5 ohio 32.323
two 2021 1.7 ohio 32.323
three 2020 3.6 nevada 562.43
four 2021 2.4 nevada 562.43
five 2020 3.3 utah 656.61
info year pop state area
id
one 2020 1.5 ohio 32.323
two 2021 1.7 ohio 32.323
three 2020 3.6 nevada 562.43
four 2021 2.4 nevada 562.43
five 2020 3.3 utah 656.61
문제 : 아래 코드를 이용하여 데이터 프레임을 구성한다.
myindex = ['김구','이봉장','안중근','윤봉길']
mycolumns= ['강남구','은평구','마포구','용산구']
mylist = list(10*onedata for onedata in range(1,17))
ㄱ.1번째 행 데이터를 조회
ㄴ.1번째와 3번째 행 데이터를 조회
ㄷ.'윤봉길'행만 조회
ㄹ.'이봉창'과 '윤봉길'행을 조회
ㅁ.'윤봉길'행의'은평구'데이터만 조회
ㅂ.'김구'와'이봉창'의 '용산구'와'은평구' 데이터 조회
ㅅ.'은평구'의 값이 100 이하인 행들을 조회
ㅇ.'은평구'의 값인 100인 행들을 조회
ㅈ.'김구'부터 '안중근'까지 '용산구'데이터를 80으로 변경
import pandas as pd
import numpy as np
myindex = ['김구','이봉창','안중근','윤봉길']
mycolumns = ['강남구','은평구','마포구','용산구']
mylist = list(10*onedata for onedata in range(1,17))
frame = pd.DataFrame(np.reshape(mylist,(4,4)),
index=myindex,
columns=mycolumns)
print(frame)
print()
print(frame.iloc[1]) #ㄱ
print()
print(frame.iloc[1,3]) #ㄴ
print()
print(frame.loc['윤봉길']) #ㄷ
print()
print(frame.loc[['이봉창','윤봉길']]) #ㄹ
print()
print(frame.loc[['윤봉길'],['은평구']]) #ㅁ
print()
print(frame.loc[['김구','이봉창'],['용산구','은평구']]) #ㅂ
print()
print(frame.loc[frame['은평구'] <= 100 ]) #ㅅ
print()
print(frame.loc[frame['은평구'] == 100 ]) #ㅇ
print()
frame.loc['김구':'안중근',['용산구']]=80 #ㅈ
print(frame)
강남구 은평구 마포구 용산구
김구 10 20 30 40
이봉창 50 60 70 80
안중근 90 100 110 120
윤봉길 130 140 150 160
강남구 50
은평구 60
마포구 70
용산구 80
Name: 이봉창, dtype: int64
80
강남구 130
은평구 140
마포구 150
용산구 160
Name: 윤봉길, dtype: int64
강남구 은평구 마포구 용산구
이봉창 50 60 70 80
윤봉길 130 140 150 160
은평구
윤봉길 140
용산구 은평구
김구 40 20
이봉창 80 60
강남구 은평구 마포구 용산구
김구 10 20 30 40
이봉창 50 60 70 80
안중근 90 100 110 120
강남구 은평구 마포구 용산구
안중근 90 100 110 120
강남구 은평구 마포구 용산구
김구 10 20 30 80
이봉창 50 60 70 80
안중근 90 100 110 80
윤봉길 130 140 150 160
두번째 solution
import pandas as pd
# 데이터 생성
myindex = ['김구','이봉창','안중근','윤봉길']
mycolumns= ['강남구','은평구','마포구','용산구']
mylist = list(10*onedata for onedata in range(1,17))
data = pd.DataFrame(
data = [mylist[i:i+4] for i in range(0, len(mylist), 4)],
index = myindex,
columns = mycolumns
)
# ㄱ. 1번째 행 데이터 조회 (iloc 사용)
print(data.iloc[0])
# ㄴ. 1번째와 3번째 행 데이터 조회
print(data.iloc[[0, 2]])
# ㄷ. '윤봉길' 행만 조회
print(data.loc['윤봉길'])
# ㄹ. '이봉창'과 '윤봉길' 행을 조회
print(data.loc[['이봉창', '윤봉길']])
# ㅁ. '윤봉길' 행의 '은평구' 데이터만 조회
print(data.loc['윤봉길', '은평구'])
# ㅂ. '김구'와 '이봉창'의 '용산구'와 '은평구' 데이터 조회
print(data.loc[['김구', '이봉창'], ['용산구', '은평구']])
# ㅅ. '은평구'의 값이 100 이하인 행들을 조회
print(data[data['은평구'] <= 100])
# ㅇ. '은평구'의 값이 100인 행들을 조회
print(data[data['은평구'] == 100])
# ㅈ. '김구'부터 '안중근'까지 '용산구' 데이터를 80으로 변경
data.loc['김구':'안중근', '용산구'] = 80
print(data)
pandas의 색인 객체는 표 형식의 데이터에서 각 로우와 칼럼에 대한 이름과 다른 메타 데이터를 저장하는 객체이다.
기존 데이터 프레임과 시리즈에서 행이나 열, 행과 열을 추려서 새데이터 프레임이나 시리즈를 생성
pandas.reindex()는 새로운 색인데 맞도록 객체를 새로 생성하는 기능을 가지고 있다.
from operator import index
import numpy as np
import pandas as pd
obj1 = pd.Series([4,7,-5,3], index=list('dabc'))
print(obj1)
obj2 = obj1.reindex(list('abcde'))
print(obj2)
print()
obj3 = pd.Series(['blue','purple','yellow'],index=[0,2,4])
print(obj3)
print()
obj4 = obj3.reindex(np.arange(6),method='ffill') # bfill 사용시 뒤에서부터 가져와서 5번에는 nan이 들어가게됨
print(obj4)
print()
frame = pd.DataFrame(np.arange(9).reshape(3,3),
index=list('acd'),
columns=['ohio','texas','california'])
print(frame)
print()
print(frame.reindex(list('abcd'))) #index 생략된 형태
print()
print(frame.reindex(columns=['texas','utah','california']))
print()
print(frame.reindex(index=list('abcd'),columns=['texas','utah','california']))
d 4
a 7
b -5
c 3
dtype: int64
a 7.0
b -5.0
c 3.0
d 4.0
e NaN
dtype: float64
0 blue
2 purple
4 yellow
dtype: object
0 blue
1 blue
2 purple
3 purple
4 yellow
5 yellow
dtype: object
ohio texas california
a 0 1 2
c 3 4 5
d 6 7 8
ohio texas california
a 0.0 1.0 2.0
b NaN NaN NaN
c 3.0 4.0 5.0
d 6.0 7.0 8.0
texas utah california
a 1 NaN 2
c 4 NaN 5
d 7 NaN 8
texas utah california
a 1.0 NaN 2.0
b NaN NaN NaN
c 4.0 NaN 5.0
d 7.0 NaN 8.0
색인 배열 또는 삭제하려는 로우나 칼럼이 제외된 리스트를 이미 가지고 있다면 drop()를 사용하여 쉽게 삭제할 수 있다.
from unittest.mock import inplace
import pandas as pd
import numpy as np
sd1 = pd.Series(np.arange(5), index=list('abcde'))
print(sd1)
print()
print(sd1.drop(['c','e']))
print()
print(sd1)
print()
sd1.drop(['c','e'], inplace=True)
print()
print(sd1)
print()
frame = pd.DataFrame(np.arange(16).reshape(4,4),
index=list('abcd'),
columns=['one','two','three','four'])
print(frame)
print()
print(frame.drop('a'))
print()
# print(frame.drop('one',axis=1))
print(frame.drop('one',axis='columns')) # 위랑 똑같음
print()
print(frame.drop(index='a',columns='one'))
a 0
b 1
c 2
d 3
e 4
dtype: int64
a 0
b 1
d 3
dtype: int64
a 0
b 1
c 2
d 3
e 4
dtype: int64
a 0
b 1
d 3
dtype: int64
one two three four
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
one two three four
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
two three four
a 1 2 3
b 5 6 7
c 9 10 11
d 13 14 15
two three four
b 5 6 7
c 9 10 11
d 13 14 15
Series의 색인은 numpy 배열의 색인과 유사하게 동작하는데, Series의 색인 정수가 아니여도 된다는 점이 다르다.
pandas에서 중요한 기능은 색인 다른 객체 간의 산술 연산이다. 객체를 연산 할 때 짝이 맞지 않는 색인 있다면 두 색인이 통합된다.
pandas 객체에도 Numpy 의 유니버셜 함수를 적용할 수 있다.
from operator import index
import numpy as np
import pandas as pd
np.random.seed(12345)
frame = pd.DataFrame(np.random.randn(4,3),
columns=['서울','부산','인천'],
index=['김가','이가','최가','오가'])
print(frame)
print()
f1 = lambda x : x.max() - x.min()
f2 = lambda x : x.sum()
result = frame.apply(f1, axis=0)
result1 = frame.apply(f2, axis=0)
print(result)
print()
print(result1)
print()
print(frame.apply(f1, axis=1))
print()
def f3(x):
return pd.Series([x.mean(),x.std()], index=['mean','std'])
result2 = frame.apply(f3,axis=0)
print(result2)
f4 = lambda x : f'{x:.2f}'
# result3 = frame.applymap(f4)
result3 = frame.map(f4)
print(result3)
print()
print(frame['인천'].map(f4))
print(frame['인천'].apply(f4))
서울 부산 인천
김가 -0.204708 0.478943 -0.519439
이가 -0.555730 1.965781 1.393406
최가 0.092908 0.281746 0.769023
오가 1.246435 1.007189 -1.296221
서울 1.802165
부산 1.684034
인천 2.689627
dtype: float64
서울 0.578905
부산 3.733659
인천 0.346769
dtype: float64
김가 0.998382
이가 2.521511
최가 0.676115
오가 2.542656
dtype: float64
서울 부산 인천
mean 0.144726 0.933415 0.086692
std 0.780852 0.753312 1.218321
서울 부산 인천
김가 -0.20 0.48 -0.52
이가 -0.56 1.97 1.39
최가 0.09 0.28 0.77
오가 1.25 1.01 -1.30
김가 -0.52
이가 1.39
최가 0.77
오가 -1.30
Name: 인천, dtype: object
김가 -0.52
이가 1.39
최가 0.77
오가 -1.30
Name: 인천, dtype: object
Series와 Dataframe을 정렬하기 위해 sort_index() 와 sort_value() 를 제공한다.
from operator import index
import pandas as pd
import numpy as np
obj1 = pd.Series(np.arange(4), index=list('dabc'))
print(obj1)
print(obj1.sort_index())
print()
frame1 = pd.DataFrame(np.arange(8).reshape(2,4),
index=['three','one'],
columns=list('dabc'))
print(frame1)
print()
print(frame1.sort_index())
print()
print(frame1.sort_index(axis=1))
print()
print(frame1.sort_index(axis=1, ascending=False))
print()
obj2 = pd.Series([4,7,-5,3])
print(obj2)
print(obj2.sort_values())
print()
data= {'second':[4,7,-3,2],'first':[0,1,0,1]}
frame2 = pd.DataFrame(data)
print(frame2)
print()
print(frame2.sort_values(by='second'))
print()
print(frame2.sort_values(by='first'))
print()
print(frame2.sort_values(by=['first','second']))
print()
print(frame2.sort_values(by=['first','second'], ascending=[False,True]))
d 0
a 1
b 2
c 3
dtype: int64
a 1
b 2
c 3
d 0
dtype: int64
d a b c
three 0 1 2 3
one 4 5 6 7
d a b c
one 4 5 6 7
three 0 1 2 3
a b c d
three 1 2 3 0
one 5 6 7 4
d c b a
three 0 3 2 1
one 4 7 6 5
0 4
1 7
2 -5
3 3
dtype: int64
2 -5
3 3
0 4
1 7
dtype: int64
second first
0 4 0
1 7 1
2 -3 0
3 2 1
second first
2 -3 0
3 2 1
0 4 0
1 7 1
second first
0 4 0
2 -3 0
1 7 1
3 2 1
second first
2 -3 0
0 4 0
3 2 1
1 7 1
second first
3 2 1
1 7 1
2 -3 0
0 4 0
Pandas의 많은 함수에서 색인 값은 유일해야 하지만 강제사항은 아니다. 중복된 색인 값의 처리 방법은 아래와 같다.
pandas 객체는 수학메서드와 통계메서드를 제공한다.
describe()는 한 번에 여러 통계 결과를 보여준다.
count : NA 값을 제외한 값의 수를 반환한다.
describe : Series 나 Dataframe의 각 칼럼에 대한 요약통계를 계산한다.
min,max : 최소 최대 값을 계산한다.
argmin,argmax : 각각 최소, 최대 값을 갖고 있는 색인의 위치를 반환한다.
idxmin, idxmax : 각각 최소, 최대 값을 갖고 있는 색인의 값을 반환한다.
quantile : 0부터 1까지의 분위수를 계산한다.
sum : 합을 계산한다.
mean : 평균을 계산한다.
var : 표본 분산의 값을 구한다.
std : 표본 정규 분산의 값을 구한다.
cumsum,cumprod : 누적합, 누적곱을 구한다.
cummin,cummax : 각각 누적 최소 값과 누적 최대 값을 계산한다.
import numpy as np
import pandas as pd
frame = pd.DataFrame(np.random.randn(1000,3),
columns=['first','second','third'])
print(frame)
frame.iloc[:4,[1,2]] = np.nan
print()
print(frame)
print()
print(frame.sum(skipna=False))
print()
print(frame.mean())
print()
print(frame.std())
print()
print(frame.describe())
print()
frame.info()
print()
print(frame.head(15))
print()
print(frame.tail(15))
first second third
0 0.280527 0.903112 0.649039
1 0.066982 -0.354154 1.385906
2 1.147796 -0.482205 0.981588
3 0.547616 -0.419585 -1.216350
4 -1.020138 -0.255480 -0.183241
.. ... ... ...
995 0.027222 0.633077 1.152884
996 -0.698076 -0.924451 -0.595086
997 0.537999 1.340982 0.404663
998 -2.064963 -0.070639 -0.043899
999 1.640277 -1.373643 -0.795923
[1000 rows x 3 columns]
first second third
0 0.280527 NaN NaN
1 0.066982 NaN NaN
2 1.147796 NaN NaN
3 0.547616 NaN NaN
4 -1.020138 -0.255480 -0.183241
.. ... ... ...
995 0.027222 0.633077 1.152884
996 -0.698076 -0.924451 -0.595086
997 0.537999 1.340982 0.404663
998 -2.064963 -0.070639 -0.043899
999 1.640277 -1.373643 -0.795923
[1000 rows x 3 columns]
first -19.523128
second NaN
third NaN
dtype: float64
first -0.019523
second -0.014238
third 0.044304
dtype: float64
first 0.968853
second 1.002653
third 0.997631
dtype: float64
first second third
count 1000.000000 996.000000 996.000000
mean -0.019523 -0.014238 0.044304
std 0.968853 1.002653 0.997631
min -2.801691 -3.638160 -2.757990
25% -0.690765 -0.676662 -0.635057
50% -0.028244 -0.028505 0.061790
75% 0.618117 0.675642 0.721573
max 3.016754 3.510771 4.159100
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 first 1000 non-null float64
1 second 996 non-null float64
2 third 996 non-null float64
dtypes: float64(3)
memory usage: 23.6 KB
first second third
0 0.280527 NaN NaN
1 0.066982 NaN NaN
2 1.147796 NaN NaN
3 0.547616 NaN NaN
4 -1.020138 -0.255480 -0.183241
5 0.475233 -0.400789 0.713184
6 -1.054172 0.431506 1.756849
7 -0.051978 0.770773 -1.348140
8 0.267001 1.338663 1.108280
9 1.104060 -0.992341 -0.198297
10 0.257997 -0.354633 0.246486
11 0.206265 -2.151476 0.055399
12 0.681084 -0.885051 1.084160
13 -0.474566 -1.169938 0.791044
14 -0.557345 -1.049161 -0.229254
first second third
985 0.553942 -0.998086 -1.110497
986 -0.002625 1.575681 0.891370
987 1.167225 -0.731039 -0.199859
988 0.380026 -1.063013 1.168833
989 -1.064825 -2.103304 -0.510612
990 1.503722 -0.501552 -0.789387
991 0.299362 -0.849080 -0.524724
992 -0.194549 1.779753 0.200757
993 0.285429 1.218760 0.757987
994 0.515989 -0.181540 1.182262
995 0.027222 0.633077 1.152884
996 -0.698076 -0.924451 -0.595086
997 0.537999 1.340982 0.404663
998 -2.064963 -0.070639 -0.043899
999 1.640277 -1.373643 -0.795923
Corr() 와 cov() 메서드는 상관관계와 공분산을 계산한다.
import pandas as pd
frame = pd.DataFrame([(100,90,70),(90,80,60),(70,50,90),(70,100,70)],
columns=['kor','eng','math'])
print(frame)
print(frame.corr())
print()
print(frame['kor'].corr(frame['eng']))
print()
print(frame.corrwith(frame['kor']))
print()
print(frame.cov())
kor eng math
0 100 90 70
1 90 80 60
2 70 50 90
3 70 100 70
kor eng math
kor 1.000000 0.308607 -0.573964
eng 0.308607 1.000000 -0.735767
math -0.573964 -0.735767 1.000000
0.3086066999241838
kor 1.000000
eng 0.308607
math -0.573964
dtype: float64
kor eng math
kor 225.000000 100.000000 -108.333333
eng 100.000000 466.666667 -200.000000
math -108.333333 -200.000000 158.333333
Pandas의 설계 목표 중 하나는 누락 데이터를 가능한 쉽게 처리할 수 있도록 하는 것이다.
dropna : 누락된 데이터가 있는 축(로우,칼럼)을 제외 시킨다.
filna : 누락된 데이터를 대신할 값을 채우거나 'ffill'또는 'bfill' 같은 보간 메서드를 적용한다.
isnull : 누락된 NA인 값을 알려주는 불리언 값이 저장된, 같은 형의 객체를 반환한다.
notnull: isnull 과 반대되는 메서드이다.
import pandas as pd
import numpy as np
data = pd.Series([1, np.nan, 3.5, np.nan, 7])
print(data)
print()
print(data.dropna())
print()
print(data.notnull())
print(data[data.notnull()])
np.random.seed(12345)
frame = pd.DataFrame(np.random.randn(7,3),
columns=['seoul','busan','incheon'])
frame.iloc[:4,1] = np.nan
frame.iloc[:2,2] = np.nan
print(frame)
print()
print(frame.fillna(0))
print()
print(frame.fillna({'busan':-5,'incheon':0}))
print()
print(frame.fillna(pd.Series([-5,0], index=['busan','incheon'])))
print()
print(frame.mean())
print()
print(frame.fillna(frame.mean()))
data ={'one':np.arange(7),
'two':np.arange(7,0,-1),
'three':[1,1,1,2,2,2,2],
'four':[0,1,2,0,1,2,3]}
frame2= pd.DataFrame(data)
print(frame2)
frame3 = frame2.set_index('three')
print(frame3)
print()
print(frame2.set_index(['two','four']))
0 1.0
1 NaN
2 3.5
3 NaN
4 7.0
dtype: float64
0 1.0
2 3.5
4 7.0
dtype: float64
0 True
1 False
2 True
3 False
4 True
dtype: bool
0 1.0
2 3.5
4 7.0
dtype: float64
seoul busan incheon
0 -0.204708 NaN NaN
1 -0.555730 NaN NaN
2 0.092908 NaN 0.769023
3 1.246435 NaN -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
seoul busan incheon
0 -0.204708 0.000000 0.000000
1 -0.555730 0.000000 0.000000
2 0.092908 0.000000 0.769023
3 1.246435 0.000000 -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
seoul busan incheon
0 -0.204708 -5.000000 0.000000
1 -0.555730 -5.000000 0.000000
2 0.092908 -5.000000 0.769023
3 1.246435 -5.000000 -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
seoul busan incheon
0 -0.204708 -5.000000 0.000000
1 -0.555730 -5.000000 0.000000
2 0.092908 -5.000000 0.769023
3 1.246435 -5.000000 -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
seoul 0.487050
busan -0.737098
incheon -0.017173
dtype: float64
seoul busan incheon
0 -0.204708 -0.737098 -0.017173
1 -0.555730 -0.737098 -0.017173
2 0.092908 -0.737098 0.769023
3 1.246435 -0.737098 -1.296221
4 0.274992 0.228913 1.352917
5 0.886429 -2.001637 -0.371843
6 1.669025 -0.438570 -0.539741
one two three four
0 0 7 1 0
1 1 6 1 1
2 2 5 1 2
3 3 4 2 0
4 4 3 2 1
5 5 2 2 2
6 6 1 2 3
one two four
three
1 0 7 0
1 1 6 1
1 2 5 2
2 3 4 0
2 4 3 1
2 5 2 2
2 6 1 3
one three
two four
7 0 0 1
6 1 1 1
5 2 2 1
4 0 3 2
3 1 4 2
2 2 5 2
1 3 6 2
A반 학생 5명과 B반 학생 5명의 국어, 영어, 수학 점수를 나타내는 데이터프레임 df_score 를 다음과 같이 만든다.
data ={
'번호' :[1,2,3,4,5,1,2,3,4,5],
'반' : ['A','A','A','A','A','B','B','B','B','B'],
'영어' :[100,90,100,80,70,90,100,70,80,90],
'국어':[90,80,90,70,100,80,90,100,70,80],
'수학':[80,100,80,90,80,100,70,80,90,100]}
a. data로 부터 "반","번호","국어","영어","수학" 을 열로 가지는 데이터 프레임을 만든다.
b. 위 데이터 프레임에 '반'과 '번호'를 제거하여 데이터 프레임을 생성한 후 각 학생의 평균을 오른쪽에 추가한다.
c. 위 데이터 프레임에 각 과목의 평균을 나타내는행 을 아래에 추가한다.
import pandas as pd
data = {
'번호': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
'반': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
'영어': [100, 90, 100, 80, 70, 90, 100, 70, 80, 90],
'국어': [90, 80, 90, 70, 100, 80, 90, 100, 70, 80],
'수학': [80, 100, 80, 90, 80, 100, 70, 80, 90, 100]}
df_score = pd.DataFrame(data, columns=["반","번호","국어","영어","수학"])
print(df_score)
print()
df_score.drop(['반','번호'],axis=1,inplace=True)
print(df_score)
print()
df_score['평균']=df_score.mean(axis=1)
print(df_score)
print()
df_score.loc['평균'] = df_score.mean(axis=0)
print(df_score)
반 번호 국어 영어 수학
0 A 1 90 100 80
1 A 2 80 90 100
2 A 3 90 100 80
3 A 4 70 80 90
4 A 5 100 70 80
5 B 1 80 90 100
6 B 2 90 100 70
7 B 3 100 70 80
8 B 4 70 80 90
9 B 5 80 90 100
국어 영어 수학
0 90 100 80
1 80 90 100
2 90 100 80
3 70 80 90
4 100 70 80
5 80 90 100
6 90 100 70
7 100 70 80
8 70 80 90
9 80 90 100
국어 영어 수학 평균
0 90 100 80 90.000000
1 80 90 100 90.000000
2 90 100 80 90.000000
3 70 80 90 80.000000
4 100 70 80 83.333333
5 80 90 100 90.000000
6 90 100 70 86.666667
7 100 70 80 83.333333
8 70 80 90 80.000000
9 80 90 100 90.000000
국어 영어 수학 평균
0 90.0 100.0 80.0 90.000000
1 80.0 90.0 100.0 90.000000
2 90.0 100.0 80.0 90.000000
3 70.0 80.0 90.0 80.000000
4 100.0 70.0 80.0 83.333333
5 80.0 90.0 100.0 90.000000
6 90.0 100.0 70.0 86.666667
7 100.0 70.0 80.0 83.333333
8 70.0 80.0 90.0 80.000000
9 80.0 90.0 100.0 90.000000
평균 85.0 87.0 87.0 86.333333