Как создать матрицу корреляции с помощью Pandas?

Опубликовано: 27 Марта, 2022

Корреляция - это статистический метод, который показывает, как связаны две переменные. Метод Pandas dataframe.corr () используется для создания корреляционной матрицы. Он используется для поиска попарной корреляции всех столбцов в кадре данных. Любые значения na автоматически исключаются. Для столбцов любого нечислового типа данных во фрейме данных он игнорируется.

Чтобы создать корреляционную матрицу с помощью панд, необходимо выполнить следующие шаги:

  1. Получите данные.
  2. Создайте DataFrame с помощью Pandas.
  3. Создайте корреляционную матрицу с помощью Pandas

Example 1:

# import pandas
import pandas as pd
  
# obtaining the data
data = {"A": [45, 37, 42],
        "B": [38, 31, 26],
        "C": [10, 15, 17]
        }
# creation of DataFrame
df = pd.DataFrame(data)
  
# creation of correlation matrix
corrM = df.corr()
  
corrM

Output:

Values at the diagonal shows the correlation of a variable with itself, hence diagonal shows the correlation 1.

Example 2:

import pandas as pd
  
data = {"A": [45, 37, 42, 50],
        "B": [38, 31, 26, 90],
        "C": [10, 15, 17, 100],
        "D": [60, 99, 23, 56],
        "E": [76, 98, 78, 90]
        }
  
df = pd.DataFrame(data)
  
corrM = df.corr()
corrM

Output:

Example 3:

import pandas as pd
  
# Integer and string values can 
# never be correlated.
data = {"A": [45, 37, 42, 50],
        "B": ["R", "O", "M", "Y"],
        }
  
df = pd.DataFrame(data)
  
corrM = df.corr()
corrM

Output:

Example 4:

import pandas as pd
  
data = {"A": [45, 37, 42, 50],
        "B": ["R", "O", "M", "Y"],
        "C": [56, 67, 68, 60],
                
        }
  
df = pd.DataFrame(data)
  
corrM = df.corr()
corrM

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

Next
Exploring Correlation in Python
Recommended Articles
Page :
Article Contributed By :
romy421kumari
@romy421kumari
Vote for difficulty
Article Tags :
  • Python pandas-dataFrame
  • Python-pandas
  • Python
Report Issue
Python

РЕКОМЕНДУЕМЫЕ СТАТЬИ