【问题标题】:How to get dummy variable when test_set and train_set have different unique values?当 test_set 和 train_set 具有不同的唯一值时如何获取虚拟变量?
【发布时间】:2020-05-08 09:57:02
【问题描述】:

train_set 是:

  type
0    a
1    b
2    c
3    d
4    e

如果我使用 pd.get_dummies,我会得到 5 列:

   type_a  type_b  type_c  type_d  type_e
0       1       0       0       0       0
1       0       1       0       0       0
2       0       0       1       0       0
3       0       0       0       1       0
4       0       0       0       0       1

测试集是:

  type
0    a
1    b
2    c
3    d

如果我使用 pd.get_dummies,我只会得到 4 列:

   type_a  type_b  type_c  type_d
0       1       0       0       0
1       0       1       0       0
2       0       0       1       0
3       0       0       0       1

我希望它是:

   type_a  type_b  type_c  type_d type_e
0       1       0       0       0      0
1       0       1       0       0      0
2       0       0       1       0      0
3       0       0       0       1      0

【问题讨论】:

    标签: python dataframe dummy-variable


    【解决方案1】:

    您可以尝试reindex 与所有想要的columns 和fill_value=0:

    pd.get_dummies(test_set).reindex(
        ["type_a", "type_b", "type_c", "type_d", "type_e"], axis=1, fill_value=0)
    

    输出

    #    type_a  type_b  type_c  type_d  type_e
    # 0       1       0       0       0       0
    # 1       0       1       0       0       0
    # 2       0       0       1       0       0
    # 3       0       0       0       1       0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-11
      • 2020-03-19
      • 1970-01-01
      • 2018-10-18
      • 2023-04-08
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多