Как создать матрицу корреляции с помощью Pandas?
Корреляция - это статистический метод, который показывает, как связаны две переменные. Метод Pandas dataframe.corr () используется для создания корреляционной матрицы. Он используется для поиска попарной корреляции всех столбцов в кадре данных. Любые значения na автоматически исключаются. Для столбцов любого нечислового типа данных во фрейме данных он игнорируется.
Чтобы создать корреляционную матрицу с помощью панд, необходимо выполнить следующие шаги:
- Получите данные.
- Создайте DataFrame с помощью Pandas.
- Создайте корреляционную матрицу с помощью Pandas
Example 1:
# import pandasimport pandas as pd # obtaining the datadata = {"A": [45, 37, 42], "B": [38, 31, 26], "C": [10, 15, 17] }# creation of DataFramedf = pd.DataFrame(data) # creation of correlation matrixcorrM = 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