[판다스 입문/산술연산] 데이터프레임 연산

2022. 10. 18. 12:53

데이터프레임은 여러 시리즈가 한데 모인 것이므로 시리즈 연산을 확장하는 개념으로 이해하는 것이 좋다.

 

목차

 

1. 데이터프레임 vs 숫자

2. 데이터프레임 vs 데이터프레임


데이터프레임 vs 숫자

 

DataFrame 객체 + 연산자(+, -, *, /) + 숫자

기존 데이터프레임의 형태를 그대로 유지한 채 원소 값만 새로운 계산값으로 바뀐다.

새로운 데이터프레임 객체가 반환된다.

 

# 예제 1-25

import pandas as pd
import seaborn as sns

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

addition = df + 10
print(addition.head())
print('\n')
print(type(addition))

seaborn 라이브러리에서 제공하는 titanic 데이터셋을 사용한다.

load_dataset() 함수로 불러온다.

titanic 데이터셋은 데이터에 관한 공부를 할 때 자주 사용되는 데이터셋 중 하나이다.

 

예제 1-25 출력 결과

 

 

데이터프레임 vs 데이터프레임

 

DataFrame1 + 연산자(+, -, *, /) + DataFrame2

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

동일한 위치의 원소끼리 계산한 값을 원래 위치에 다시 입력하여 데이터프레임을 만든다.

데이터프레임 중에서 어느 한쪽에 원소가 존재하지 않거나 NaN인 경우 연산 결과는 NaN으로 처리된다.

 

# 예제 1-26

import pandas as pd
import seaborn as sns

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

addition = df + 10
print(addition.tail())
print('\n')
print(type(addition))
print('\n')

subtraction = addition - df
print(subtraction.tail())
print('\n')
print(type(subtraction))

 

예제 1-26 출력 결과


파이썬 머신러닝 판다스 데이터분석
저자 : 오승환
출판 : 정보문화사
발매 : 2019.06.05

 

BELATED ARTICLES

more