본문 바로가기
Study/혼자 공부하는 판다스

혼자 공부하는 판다스 - 인덱스 활용과 산술 연산

by Wanooky 2022. 3. 15.

특정 열을 행 인덱스로 설정

DataFame.set_index[['열 이름'] 또는 "열 이름"]

 

exam_data = {'이름': ['서준','우현','인아'],
             '수학': [90,80,70],
             '영어': [98,89,95],
             '음악': [85, 95, 100],
             '체육': [100,90,90]}
        
df = pd.DataFrame(exam_data)

ndf = pd.set_index(['이름'])
print(ndf)

ndf2 = pd.set_index('음악')
print(ndf2)

ndf3 = ndf.set_index(['수학','음악'])
print(ndf3)

    수학  영어   음악   체육
이름                  
서준  90  98   85  100
우현  80  89   95   90
인아  70  95  100   90
     수학  영어   체육
음악              
85   90  98  100
95   80  89   90
100  70  95   90
        영어   체육
수학 음악          
90 85   98  100
80 95   89   90
70 100  95   90

행 인덱스를 재배열하는 방법

DataFrame.reindex(새로운 인덱스 배열)

 

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'])
print(df)

new_index = ['r0', 'r1', 'r2', 'r3', 'r4']
ndf = df.reindex(new_index)
print(ndf)

ndf2 = df.reindex(new_index, fill_value=0)
print(ndf2)

    c0  c1  c2  c3  c4
r0   1   4   7  10  13
r1   2   5   8  11  14
r2   3   6   9  12  15
     c0   c1   c2    c3    c4
r0  1.0  4.0  7.0  10.0  13.0
r1  2.0  5.0  8.0  11.0  14.0
r2  3.0  6.0  9.0  12.0  15.0
r3  NaN  NaN  NaN   NaN   NaN
r4  NaN  NaN  NaN   NaN   NaN
    c0  c1  c2  c3  c4
r0   1   4   7  10  13
r1   2   5   8  11  14
r2   3   6   9  12  15
r3   0   0   0   0   0
r4   0   0   0   0   0

 

행 인덱스 초기화

DataFrame.reset_index()

 

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'])
print(df)

ndf = df.reset_index()
print(ndf)

    c0  c1  c2  c3  c4
r0   1   4   7  10  13
r1   2   5   8  11  14
r2   3   6   9  12  15
  index  c0  c1  c2  c3  c4
0    r0   1   4   7  10  13
1    r1   2   5   8  11  14
2    r2   3   6   9  12  15

행 인덱스 기준으로 데이터 프레임 정렬

DataFrame.sort_index()

ascending=False 이면 내림차순, ascending=True 이면 오름차순

 

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'])
print(df)

ndf = df.sort_index(ascending=False)
print(ndf)

    c0  c1  c2  c3  c4
r0   1   4   7  10  13
r1   2   5   8  11  14
r2   3   6   9  12  15
    c0  c1  c2  c3  c4
r2   3   6   9  12  15
r1   2   5   8  11  14
r0   1   4   7  10  13

특정 열의 데이터 값을 기준으로 데이터 프레임 정렬

DataFrame.sort_values()

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'])
print(df)

ndf = df.sort_values(by='c1', ascending=False)
print(ndf)

    c0  c1  c2  c3  c4
r0   1   4   7  10  13
r1   2   5   8  11  14
r2   3   6   9  12  15
    c0  c1  c2  c3  c4
r2   3   6   9  12  15
r1   2   5   8  11  14
r0   1   4   7  10  13

 

산술 연산

 

시리즈와 숫자 연산

Series + 연산자 + 숫자

student = pd.Series({'국어':100, '영어':80, '수학':90})
print(student)

percentage = student/200

print(percentage)
print(type(percentage))



국어    100
영어     80
수학     90
dtype: int64
국어    0.50
영어    0.40
수학    0.45
dtype: float64
<class 'pandas.core.series.Series'>

 

시리즈끼리 사칙연산

Series + 사칙연산 + Series

 

student1 = pd.Series({'국어':100, '영어':80, '수학':90})
student2 = pd.Series({'국어':80, '영어':90, '수학':80})

addition = student1 + student2
subtraction = student1 - student2
multiplication = student1 * student2
division = student1/student2
print(type(division))

result = pd.DataFrame([addition, subtraction, multiplication, division], index=['덧셈','뺄셈','곱셈','나눗셈'])

print(result)


          국어           영어        수학
덧셈    180.00   170.000000   170.000
뺄셈     20.00   -10.000000    10.000
곱셈   8000.00  7200.000000  7200.000
나눗셈     1.25     0.888889     1.125

 

판다스는 같은 인덱스를 찾아 정렬한 후 같은 인덱스의 데이터 값끼리 덧셈한다.

동일한 인덱스가 양쪽에 모두 존재하더라도 한쪽이 NaN이면 계산이 되지 않는다.

student1 = pd.Series({'국어':100, '영어':80, '수학':90})
student2 = pd.Series({'수학':80 ,'국어':90})

print(student1)
print(student2)


addition = student1 + student2
subtraction = student1 - student2
multiplication = student1 * student2
division = student1/student2
print(type(division))

result = pd.DataFrame([addition, subtraction, multiplication, division], index=['덧셈','뺄셈','곱셈','나눗셈'])

print(result)



국어    100
영어     80
수학     90
dtype: int64
수학    80
국어    90
dtype: int64
<class 'pandas.core.series.Series'>
              국어        수학  영어
덧셈    190.000000   170.000 NaN
뺄셈     10.000000    10.000 NaN
곱셈   9000.000000  7200.000 NaN
나눗셈     1.111111     1.125 NaN

연산 메소드

Series.add(series2, fill_value = 0) NaN 대신 채우고 싶은 값을 fill_value 이용해서

 

student1 = pd.Series({'국어':100, '영어':80, '수학':90})
student2 = pd.Series({'수학':80 ,'국어':90})

sr_add = student1.add(student2, fill_value=0)
sr_sub = student1.sub(student2, fill_value=0)
sr_mul = student1.mul(student2, fill_value=0)
sr_div = student1.div(student2, fill_value=0)

result = pd.DataFrame([sr_add, sr_sub, sr_mul, sr_div], index=['덧셈','뺄셈','곱셈','나눗셈'])
print(result)


              국어        수학    영어
덧셈    190.000000   170.000  80.0
뺄셈     10.000000    10.000  80.0
곱셈   9000.000000  7200.000   0.0
나눗셈     1.111111     1.125   inf

 

데이터 프레임 연산

DataFrame + 연산자 + 숫자

 

#데이터 프레임 연산 : DataFrame + 연산자 + 숫자
import seaborn as sns

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','fare']]
print(df.head())
print(type(df))

addition = df + 10
print(addition.head())
print(type(addition))


    age     fare
0  22.0   7.2500
1  38.0  71.2833
2  26.0   7.9250
3  35.0  53.1000
4  35.0   8.0500
<class 'pandas.core.frame.DataFrame'>
    age     fare
0  32.0  17.2500
1  48.0  81.2833
2  36.0  17.9250
3  45.0  63.1000
4  45.0  18.0500
<class 'pandas.core.frame.DataFrame'>

데이터프레임은 같은 행 같은 열 위치에 있는 원소끼리 계산한다.

만약 한쪽에 원소가 존재하지 않거나 NaN이면 연산 결과를 NaN으로 처리한다.

 

titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','fare']]
print(df.tail())
print(type(df))

addition = df + 10
print(addition.tail())
print(type(addition))

subtraction = addition - df
print(subtraction.tail())
print(type(subtraction))



      age   fare
886  27.0  13.00
887  19.0  30.00
888   NaN  23.45
889  26.0  30.00
890  32.0   7.75
<class 'pandas.core.frame.DataFrame'>
      age   fare
886  37.0  23.00
887  29.0  40.00
888   NaN  33.45
889  36.0  40.00
890  42.0  17.75
<class 'pandas.core.frame.DataFrame'>
      age  fare
886  10.0  10.0
887  10.0  10.0
888   NaN  10.0
889  10.0  10.0
890  10.0  10.0
<class 'pandas.core.frame.DataFrame'>