【发布时间】:2016-10-13 05:25:39
【问题描述】:
TLDR:使用特定编码转换将有序类别编码为数字的最简洁方法是什么? (即保留类别有序性质的类别)。
["弱","正常","强"] --> [0,1,2]
假设我有一个类似于来自here 的示例的 ordered 分类变量:
import pandas as pd
raw_data = {'patient': [1, 1, 1, 2, 2],
'obs': [1, 2, 3, 1, 2],
'treatment': [0, 1, 0, 1, 0],
'score': ['strong', 'weak', 'normal', 'weak', 'strong']}
df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
df
obs treatment score
0 1 strong
1 1 weak
2 1 normal
3 2 weak
4 2 strong
我可以创建一个函数并将其应用于我的数据框以获得所需的对话:
def score_to_numeric(x):
if x=='strong':
return 3
if x=='normal':
return 2
if x=='weak':
return 1
df['score_num'] = df['score'].apply(score_to_numeric)
df
obs treatment score score_num
0 1 strong 3
1 1 weak 1
2 1 normal 2
3 2 weak 1
4 2 strong 3
我的问题:有什么办法可以内联吗? (无需指定单独的“score_to_numeric”函数。
也许使用某种 lambda 或替换功能?或者,这篇SO 文章表明 Sklearn 的 LabelEncoder() 非常强大,并且通过扩展可能有某种方法来处理这个问题,但我还没有弄清楚......
【问题讨论】:
标签: python pandas encoding types scikit-learn