【问题标题】:Python: Encode ordered categories/factors to numeric w/ specific encoding conversionPython:将有序类别/因子编码为带有特定编码转换的数字
【发布时间】: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


    【解决方案1】:

    您可以将map() 与包含您的映射的字典结合使用:

    In [5]: d = {'strong':3, 'normal':2, 'weak':1}
    
    In [7]: df['score_num'] = df.score.map(d)
    
    In [8]: df
    Out[8]:
       patient  obs  treatment   score  score_num
    0        1    1          0  strong          3
    1        1    2          1    weak          1
    2        1    3          0  normal          2
    3        2    1          1    weak          1
    4        2    2          0  strong          3
    

    【讨论】:

    • 当然!地图!我可以结合这两个部分来获得我正在寻找的单线: df['score_num'] = df.score.map({'strong':3, 'normal':2, 'weak':1} )
    • @Afflatus,你当然也可以这样做,但我认为单独保存字典更容易(更简洁),所以你可以多次使用它,更新它等等。
    • 是的,但在我的情况下,我必须对大约 10 个分类变量进行不同的编码......我现在真的不想考虑为所有字典命名......如果我稍后需要,我回去提取代码。
    猜你喜欢
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2019-07-25
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多