【问题标题】:Python way to convert categorical values into binary in the same columnPython方法将分类值转换为同一列中的二进制值
【发布时间】:2016-04-24 09:19:36
【问题描述】:

Gurus,我们正在寻找一种 Python 方式(python 2.7)将列中的分类值转换为二进制值到单个新列中。示例:在“Loan_status”列中,

 Loan_Status
 Charged Off
 Default
 Fully Paid
 Current
 Does not meet the credit policy. Status:1
 Does not meet the credit policy. Status:0

我们正在尝试将“Charged Off”、“Default”变为“0”、“Fully Paid”、“Current”变为“1”,并删除任何包含“不符合信用政策”的行。状态: 1”和“不符合信用政策。状态:0”。

期望的输出:

 Loan_Status
 0
 0
 1
 1

有什么pythonic方法可以做到吗? Pandas get_dummies 会生成多个列,所以它似乎不起作用。谢谢!

【问题讨论】:

    标签: python-2.7 pandas scikit-learn


    【解决方案1】:

    让我们定义一个正负类标签列表。

    positive = ['Fully Paid', 'Current']
    negative = ['Charged Off', 'Default']
    

    首先,过滤数据框以查找对您的模型无效的行。我们可以使用isin 来过滤任何一个中的值

    filtered_df = df[df['Loan_Status'].isin(positive + negative)].copy()
    

    其次,为正面标签创建一个新列。如果需要01,我们可以将布尔结果转换为int

    filtered_df['Loan_Status'] = filtered_df['Loan_Status'].isin(positive).astype(int)
    

    【讨论】:

    • 很好的答案!谢谢!
    • 嗯遇到一个新问题:如果我像这样过滤了多个列,有什么简单的方法可以将它们组合成一个大而干净的表吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2020-09-18
    • 2019-03-06
    • 2021-03-06
    • 2023-02-13
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多