热线电话:13121318867

登录
2019-03-22 阅读量: 830
为分类变量编码

有时同一个分类变量可能会有两种表现方式。如,温度可能被标记为“High”, “Medium”, “Low”,“H”, “low”。这里 “High” 和 “H”都代表同一类别。同理, “Low” 和“low”也是同一类别。但Python会把它们当作不同的类别。

一些类别的频数非常低,把它们归为一类是个好主意。

这里我们定义了一个函数,以字典的方式输入数值,用‘replace’函数进行编码。

#使用Pandas replace函数定义新函数:

def coding(col, codeDict):

colCoded = pd.Series(col, copy=True)

for key, value in codeDict.items():

colCoded.replace(key, value, inplace=True)

return colCoded

​

#把贷款状态LoanStatus编码为Y=1, N=0:

print 'Before Coding:'

print pd.value_counts(data["Loan_Status"])

data["Loan_Status_Coded"] = coding(data["Loan_Status"], {'N':0,'Y':1})

print '\nAfter Coding:'

print pd.value_counts(data["Loan_Status_Coded"])

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据