【问题标题】:Combine 2 dataframe and then separate them合并 2 个数据框,然后将它们分开
【发布时间】:2018-05-01 06:36:03
【问题描述】:

我有 2 个具有相同列标题的数据框。我希望对它们都执行热编码。我无法一一执行。我希望将两个数据帧附加在一起,然后执行热编码,然后将它们分成两个数据帧,每个数据帧都带有标题。

下面的代码一个一个地执行热编码,而不是合并它们然后进行热编码。

train = pd.get_dummies(train, columns= ['is_discount', 'gender', 'city'])
test = pd.get_dummies(test, columns= ['is_discount', 'gender', 'city'])

【问题讨论】:

    标签: python pandas dataframe one-hot-encoding


    【解决方案1】:

    将 concat 与键一起使用,然后除以,即

    #Example Dataframes 
    train = pd.DataFrame({'x':[1,2,3,4]})
    test = pd.DataFrame({'x':[4,2,5,0]})
    
    # Concat with keys
    temp = pd.get_dummies(pd.concat([train,test],keys=[0,1]), columns=['x'])
    
    # Selecting data from multi index 
    train,test = temp.xs(0),temp.xs(1)
    

    输出:

    #火车 x_0 x_1 x_2 x_3 x_4 x_5 0 0 1 0 0 0 0 1 0 0 1 0 0 0 2 0 0 0 1 0 0 3 0 0 0 0 1 0 #测试 x_0 x_1 x_2 x_3 x_4 x_5 0 0 0 0 0 1 0 1 0 0 1 0 0 0 2 0 0 0 0 0 1 3 1 0 0 0 0 0

    【讨论】:

      猜你喜欢
      • 2019-09-22
      • 2021-07-06
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2018-01-09
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多