Skip to content

Commit 14334a3

Browse files
committed
<add> : add pd_calculate.py
- add series arithmatic calculation - add dataframe arithmatic calculation
1 parent 7a8da8b commit 14334a3

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

PandasPractice/pd_calculate.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
"""
2+
Pandas 객체의 산술연산은 내부적으로 3단계를 거쳐 수행된다.
3+
1. 행/인덱스 기준으로 모든 원소를 정렬
4+
2. 동일한 위치에 있는 원소끼리 일대일로 대응시킴
5+
3. 일대일 대응되는 원손끼리 연산처리. 대응되는 원소가 없으면 NaN으로 처리
6+
NaN = np.nan(NaN)
7+
"""
8+
9+
import pandas as pd
10+
import seaborn as sns
11+
import numpy as np
12+
13+
'''
14+
####################################################################### release quotation above
15+
student1 = pd.Series({'국어':100, '영어':80, '수학':90})
16+
print(student1, '\n')
17+
18+
"""
19+
Series 객체 + 연산자 + 숫자
20+
과목별 점수를 200으로 나누기
21+
"""
22+
23+
percentage_student1 = student1/200
24+
print(percentage_student1, '\n')
25+
print(type(percentage_student1), '\n')
26+
27+
28+
"""
29+
Series + 연산자 + Series
30+
시리즈의 모든 인덱스에 대하여 인덱스를 가진 원소끼리 계산한다.
31+
1. 두 시리즈간의 사칙 연산을 먼저 계산
32+
2. DataFrame() 메서드를 사용하여 결과를 하나의 데이터프레임으로 합친다.
33+
34+
student1과 student2에 인덱스로 주어진 과목명의 순서가 다르지만
35+
pandas는 같은 과목명을 찾아 정렬한 후 같은 과목명의 점수끼리 연산하고
36+
새로운 시리즈 객체를 반환한다.
37+
38+
유효하지 않은 연산: 인덱스 대응 불가, 한 쪽이라도 대응값이 NaN인 경우
39+
에 대해서는 NaN 반환. NaN = np.nan(NaN)
40+
"""
41+
student1 = pd.Series({'국어':100, '영어':80, '수학':90})
42+
student2 = pd.Series({'영어':100, '수학':80, '국어':90})
43+
44+
addition = student1 + student2
45+
subtraction = student1 - student2
46+
multiplication = student1 * student2
47+
division = student1/student2
48+
print(type(division))
49+
print('\n')
50+
51+
result = pd.DataFrame([addition,subtraction,multiplication,division], index=['덧셈 결과', '뺄셈 결과', '곱셈 결과', '나눗셈 결과'])
52+
print(result)
53+
54+
"""
55+
Series + 연산 메서드(시리즈)
56+
연산 메서드를 사용하면 fill_value 옵션으로 NaN값을 대체할 값을 지정할 수 있다.
57+
"""
58+
student1 = pd.Series({'국어':np.nan, '영어':80, '수학':90})
59+
student2 = pd.Series({'수학':80, '국어':90})
60+
61+
sr_add = student1.add(student2, fill_value=0)
62+
sr_sub = student1.sub(student2, fill_value=0)
63+
sr_mul = student1.mul(student2, fill_value=0)
64+
sr_div = student1.div(student2, fill_value=0) # 영어 점수 80을 영어 점수 0으로 나누어서 inf(무한대) 값이 나옴.
65+
66+
result = pd.DataFrame([sr_add, sr_sub, sr_mul, sr_div], index=['덧셈 결과', '뺄셈 결과', '곱셈 결과', '나눗셈 결과'])
67+
print(result)
68+
####################################################################### release quotation below
69+
'''
70+
71+
"""
72+
DataFrame 연산.
73+
시리즈 연산의 확장이다.
74+
DataFrame 객체 + 연산자 + 숫자
75+
1. 행/열 인덱스 기준으로 정렬하고 일대일 대응되는 원소끼리 연산을 처리.
76+
어느 한 쪽에 원소가 존재하지 않거나 값이 NaN이면 연산 결과는 NaN으로 처리.
77+
2. 새로운 DataFrame 객체로 반환된다.
78+
seaborn 내장 데이터셋 참고
79+
"""
80+
titanic = sns.load_dataset('titanic')
81+
df = titanic.loc[:, ['age', 'fare']] # age, fare column의 모든 열 표시
82+
print(df.head(),'\n') # 첫 5행 표시
83+
print(type(df),'\n')
84+
85+
addition = df + 10
86+
print(addition.head(),'\n') # 첫 5행 표시
87+
print(type(addition),'\n')
88+
89+
"""
90+
DataFrame 연산
91+
DataFrame + DataFrame
92+
93+
1. 각 DataFrame의 같은 행, 열 위치에 있는 원소끼리 게산.
94+
2. 어느 한 쪽에 원소가 존재하지 않거나 값이 NaN이면 연산 결과는 NaN으로 처리.
95+
"""
96+
subtraction = addition - df
97+
print(subtraction.tail(), '\n') # 마지막 5행 표시
98+
print(type(subtraction),'\n')

0 commit comments

Comments
 (0)