【问题标题】:Converting Multiple Dummy Variables into one Column [duplicate]将多个虚拟变量转换为一列[重复]
【发布时间】:2019-12-04 20:39:45
【问题描述】:

我想转换一个如下所示的表格:

            Blue    Green    Red
Thing 1     No      Yes      No
Thing 2     Yes     No       No
Thing 3     Yes     No       No

进入这种风格:

            Color
Thing 1     Green
Thing 2     Blue
Thing 3     Blue

在 python 或 pandas 中有没有很好的方法来做到这一点?这些表格样式有名称吗?

【问题讨论】:

  • 这些方法的名称在第一种情况下是“虚拟”或“指标”变量,在第二种情况下是分类变量。例如,参见pandas.DataFrame.get_dummies(),它执行相反方向的转换(分类为假人)。
  • 只需要加上df.eq('yes')

标签: python pandas


【解决方案1】:

只需使用idxmax:

df.eq('Yes').idxmax(axis=1)

输出

Thing 1    Green
Thing 2     Blue
Thing 3     Blue
dtype: object

【讨论】:

    【解决方案2】:

    如果每一行都有一个“是”,你可以这样做

    df.eq('Yes') @ df.columns
    

    输出:

    Thing 1    Green
    Thing 2     Blue
    Thing 3     Blue
    dtype: object
    

    【讨论】:

      【解决方案3】:

      用途:

      df.where(df.eq('Yes')).stack().reset_index(level=1)['level_1']
      
      Thing 1    Green
      Thing 2     Blue
      Thing 3     Blue
      Name: level_1, dtype: object
      

      【讨论】:

        猜你喜欢
        • 2018-03-22
        • 2015-10-28
        • 2020-11-28
        • 2015-08-02
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 2021-01-01
        相关资源
        最近更新 更多