Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Pandas에서 두 열 간의 상관 관계를 얻는 방법은 무엇입니까?

<시간/>

.corr()을 사용할 수 있습니다. Pandas에서 두 열 간의 상관 관계를 가져오는 방법입니다. 예를 들어 이 방법을 적용하는 방법을 살펴보겠습니다.

단계

  • 크기가 변경 가능한 2차원 테이블 형식 데이터 df 생성 .
  • 입력 DataFrame, df 인쇄 .
  • 두 변수 초기화, col1col2 , 상관 관계를 찾고자 하는 열을 할당합니다.
  • col1 간의 상관관계 찾기 df[col1].corr(df[col2])를 사용하여 col2와 상관관계 값을 변수 corr에 저장합니다.
  • 상관관계 값을 인쇄합니다. corr.

예시

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df

col1, col2 = "x", "y"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)

col1, col2 = "x", "x"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)

col1, col2 = "x", "z"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)

col1, col2 = "y", "x"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)

출력

Input DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Correlation between x and y is: 0.41
Correlation between x and x is: 1.0
Correlation between x and z is: 0.72
Correlation between y and x is: 0.41