본문 바로가기
기술스택을 쌓아보자/Python

pandas 번역: Computational tools, pandas의 연산툴 (pandas User guide 번역/pandas 기초 입문/Pandas 간단 요약)

by 소리331 2021. 1. 6.
반응형

저는 금융데이터를 주로 다루는데요,

금융 데이터는 대부분이 정량데이터로 이루어져 있다보니 이런 계산 툴들이 잘 구현되어 있습니다. 

복잡한 계산도 코드 한 두줄로 간단히!

중간에 잘 번역이 안되는건 그냥 번역기 돌리고 영어 원문도 같이 첨부했습니다.

 

다른 유저가이드 번역 보러가기


Statistical functions

 

Percent change

 

Series와 DataFrame는 기간동안의 변화%를 구하기 위해 pct_change()를 제공합니다.(계산전. nan 값을 채우기 위해fill_method 를 사용합니다.

In [1]: ser = pd.Series(np.random.randn(8))

In [2]: ser.pct_change()
Out[2]: 
0         NaN
1   -1.602976
2    4.334938
3   -0.247456
4   -2.067345
5   -1.142903
6   -1.688214
7   -9.759729
dtype: float64
In [3]: df = pd.DataFrame(np.random.randn(10, 4))

In [4]: df.pct_change(periods=3)
Out[4]: 
          0         1         2         3
0       NaN       NaN       NaN       NaN
1       NaN       NaN       NaN       NaN
2       NaN       NaN       NaN       NaN
3 -0.218320 -1.054001  1.987147 -0.510183
4 -0.439121 -1.816454  0.649715 -4.822809
5 -0.127833 -3.042065 -5.866604 -1.776977
6 -2.596833 -1.959538 -2.111697 -3.798900
7 -0.117826 -2.169058  0.036094 -0.067696
8  2.492606 -1.357320 -1.205802 -1.558697
9 -1.012977  2.324558 -1.003744 -0.371806

 

 

Covariance

 

Series.cov()는 series 간의 공분산을 계산합니다. (결측치는 제외하고 연산합니다)

In [5]: s1 = pd.Series(np.random.randn(1000))

In [6]: s2 = pd.Series(np.random.randn(1000))

In [7]: s1.cov(s2)
Out[7]: 0.0006801088174310875

유사하게 DataFrame.cov() 도 적용이 가능합니다. df내의 열에 대해서 계산합니다. 역시 Nan은 제외합니다.

Note!

Assuming the missing data are missing at random this results in an estimate for the covariance matrix which is unbiased. However, for many applications this estimate may not be acceptable because the estimated covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimated correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See Estimation of covariance matricesfor more details.

결측 데이터가 랜덤하게 결측되었다고 가정하면 공분산 행렬에 대한 추정치가 됩니다. 그러나 추정된 공분산 행렬이 양의 반정확성을 보장하지 않기 때문에 대부분의 애플리케이션에서 이 추정치는 허용되지 않을 수 있습니다. 이는 1보다 큰 절대값 및/또는 비가역 공분산 행렬을 갖는 추정된 상관 관계를 초래할 수 있습니다. 자세한 내용은 공분산 행렬 추정을 참조하십시오.

 

In [8]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=["a", "b", "c", "d", "e"])

In [9]: frame.cov()
Out[9]: 
          a         b         c         d         e
a  1.000882 -0.003177 -0.002698 -0.006889  0.031912
b -0.003177  1.024721  0.000191  0.009212  0.000857
c -0.002698  0.000191  0.950735 -0.031743 -0.005087
d -0.006889  0.009212 -0.031743  1.002983 -0.047952
e  0.031912  0.000857 -0.005087 -0.047952  1.042487

 

DataFrame.cov 는 min_periods 옵션도 사용이 가능합니다. min_periods 키워드는 유효한 값을 얻기 위한 최소한으로 요구되는 데이터의 갯수를 의미합니다.(위의 note의 부분을 보충하는 점이라고 볼 수도 있겠네요)

In [10]: frame = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])

In [11]: frame.loc[frame.index[:5], "a"] = np.nan

In [12]: frame.loc[frame.index[5:10], "b"] = np.nan

In [13]: frame.cov()
Out[13]: 
          a         b         c
a  1.123670 -0.412851  0.018169
b -0.412851  1.154141  0.305260
c  0.018169  0.305260  1.301149

In [14]: frame.cov(min_periods=12)
Out[14]: 
          a         b         c
a  1.123670       NaN  0.018169
b       NaN  1.154141  0.305260
c  0.018169  0.305260  1.301149

 

 

Correlation

 

상관관계는 corr() 함수로 계산이 가능합니다. corr함수 내의 method 파라미터를 이용해서, 상관관계를 구하는 방식을 변경할 수 있습니다.

method name 상관관계의 종류
pearson (default) Standard correlation coefficient
kendall Kendall Tau correlation coefficient
spearman Spearman rank correlation coefficient

세 방식 모두 각각 완전한 짝을 이뤄 계산합니다. 각 개별 방식에 대해서는  위키피디아에 해당 상관관계 계수에 대한 문서들을 읽어보세요

Note! : 공분산 섹션에서 언급되었던 주의사항(Note!), 꼭 읽어보세요!

 

In [15]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=["a", "b", "c", "d", "e"])

In [16]: frame.iloc[::2] = np.nan

# Series with Series
In [17]: frame["a"].corr(frame["b"])
Out[17]: 0.013479040400098775

In [18]: frame["a"].corr(frame["b"], method="spearman")
Out[18]: -0.007289885159540637

# Pairwise correlation of DataFrame columns
In [19]: frame.corr()
Out[19]: 
          a         b         c         d         e
a  1.000000  0.013479 -0.049269 -0.042239 -0.028525
b  0.013479  1.000000 -0.020433 -0.011139  0.005654
c -0.049269 -0.020433  1.000000  0.018587 -0.054269
d -0.042239 -0.011139  0.018587  1.000000 -0.017060
e -0.028525  0.005654 -0.054269 -0.017060  1.000000

상관관계 계산시, 정량데이터가 아닌경우는 자동적으로 제외됩니다! (연산대상이 아님)

cov(공분산) 처럼 corr(상관관계) 또한 min_periods 키워드를 사용합니다. 해당 키워드는 pandas 0.24.0 버전에서 추가된 내용이라 이전 버전을 사용하시는 분들은 적용되지 않는 내용입니다.

In [20]: frame = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])

In [21]: frame.loc[frame.index[:5], "a"] = np.nan

In [22]: frame.loc[frame.index[5:10], "b"] = np.nan

In [23]: frame.corr()
Out[23]: 
          a         b         c
a  1.000000 -0.121111  0.069544
b -0.121111  1.000000  0.051742
c  0.069544  0.051742  1.000000

In [24]: frame.corr(min_periods=12)
Out[24]: 
          a         b         c
a  1.000000       NaN  0.069544
b       NaN  1.000000  0.051742
c  0.069544  0.051742  1.000000

 

corr 함수에서 method 인자또한 사용이 가능한데, 이 경우 method에 함수를 넣어야합니다. 함수의 경우 input은 2개의 ndarray여야 하고, 결과값은 single value 여야합니다. histogram intersection을 이용한 상관관계를 구하고 싶다고 가정해봅시다.

# histogram intersection
In [25]: def histogram_intersection(a, b):
   ....:     return np.minimum(np.true_divide(a, a.sum()), np.true_divide(b, b.sum())).sum()
   ....: 

In [26]: frame.corr(method=histogram_intersection)
Out[26]: 
          a          b          c
a  1.000000  -6.404882  -2.058431
b -6.404882   1.000000 -19.255743
c -2.058431 -19.255743   1.000000

 

 corrwith()은 서로 다른 두 dataframe 간에 상관관계를 구할 수 있는 함수입니다. 서로 다른 시리즈 안의 like-labeled series 간의 상관관계를 구해줍니다.\

In [27]: index = ["a", "b", "c", "d", "e"]

In [28]: columns = ["one", "two", "three", "four"]

In [29]: df1 = pd.DataFrame(np.random.randn(5, 4), index=index, columns=columns)

In [30]: df2 = pd.DataFrame(np.random.randn(4, 4), index=index[:4], columns=columns)

In [31]: df1.corrwith(df2)
Out[31]: 
one     -0.125501
two     -0.493244
three    0.344056
four     0.004183
dtype: float64

In [32]: df2.corrwith(df1, axis=1)
Out[32]: 
a   -0.675817
b    0.458296
c    0.190809
d   -0.186275
e         NaN
dtype: float64

 

 

Data ranking

 

 rank() 함수는 dataframe의 행 또는 열을 순위를 매겨줍니다. nan은 자동으로 제외됩니다.

In [36]: df = pd.DataFrame(np.random.randn(10, 6))

In [37]: df[4] = df[2][:5]  # some ties

In [38]: df
Out[38]: 
          0         1         2         3         4         5
0 -0.904948 -1.163537 -1.457187  0.135463 -1.457187  0.294650
1 -0.976288 -0.244652 -0.748406 -0.999601 -0.748406 -0.800809
2  0.401965  1.460840  1.256057  1.308127  1.256057  0.876004
3  0.205954  0.369552 -0.669304  0.038378 -0.669304  1.140296
4 -0.477586 -0.730705 -1.129149 -0.601463 -1.129149 -0.211196
5 -1.092970 -0.689246  0.908114  0.204848       NaN  0.463347
6  0.376892  0.959292  0.095572 -0.593740       NaN -0.069180
7 -1.002601  1.957794 -0.120708  0.094214       NaN -1.467422
8 -0.547231  0.664402 -0.519424 -0.073254       NaN -1.263544
9 -0.250277 -0.237428 -1.056443  0.419477       NaN  1.375064

In [39]: df.rank(1)
Out[39]: 
     0    1    2    3    4    5
0  4.0  3.0  1.5  5.0  1.5  6.0
1  2.0  6.0  4.5  1.0  4.5  3.0
2  1.0  6.0  3.5  5.0  3.5  2.0
3  4.0  5.0  1.5  3.0  1.5  6.0
4  5.0  3.0  1.5  4.0  1.5  6.0
5  1.0  2.0  5.0  3.0  NaN  4.0
6  4.0  5.0  3.0  1.0  NaN  2.0
7  2.0  5.0  3.0  4.0  NaN  1.0
8  2.0  5.0  3.0  4.0  NaN  1.0
9  2.0  3.0  1.0  4.0  NaN  5.0

 

rank는 ascending 인자를 가지는데, default값은 True입니다. 오름차순, 내림차순에 관련된 옵션입니다!

 rank 의 method 파라미터를 이용하면 다양한 방법을 통해 rank를 구할 수 있스빈다.

  • average : average rank of tied group

  • min : lowest rank in the group

  • max : highest rank in the group

  • first : ranks assigned in the order they appear in the array

반응형

댓글