如何用python进行相关性分析,如何检查python中连续变量和分类变量之间的相关性?...

I have a dataset including categorical variables(binary) and continuous variables. I'm trying to apply a linear regression model for predicting a continuous variable. Can someone please let me know how to check for correlation among the categorical variables and the continuous target variable.

Current Code:

import pandas as pd

df_hosp = pd.read_csv('C:\Users\LAPPY-2\Desktop\LengthOfStay.csv')

data = df_hosp[['lengthofstay', 'male', 'female', 'dialysisrenalendstage', 'asthma', \

'irondef', 'pneum', 'substancedependence', \

'psychologicaldisordermajor', 'depress', 'psychother', \

'fibrosisandother', 'malnutrition', 'hemo']]

print data.corr()

All of the variables apart from lengthofstay are categorical. Should this work?

解决方案

Convert your categorical variable into dummy variables here and put your variable in numpy.array. For example:

data.csv:

age,size,color_head

4,50,black

9,100,blonde

12,120,brown

17,160,black

18,180,brown

Extract data:

import numpy as np

import pandas as pd

df = pd.read_csv('data.csv')

df:

zT77K.png

Convert categorical variable color_head into dummy variables:

df_dummies = pd.get_dummies(df['color_head'])

del df_dummies[df_dummies.columns[-1]]

df_new = pd.concat([df, df_dummies], axis=1)

del df_new['color_head']

df_new:

Q9C9O.png

Put that in numpy array:

x = df_new.values

Compute the correlation:

correlation_matrix = np.corrcoef(x.T)

print(correlation_matrix)

Output:

array([[ 1. , 0.99574691, -0.23658011, -0.28975028],

[ 0.99574691, 1. , -0.30318496, -0.24026862],

[-0.23658011, -0.30318496, 1. , -0.40824829],

[-0.28975028, -0.24026862, -0.40824829, 1. ]])

See :

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值