合并 2 个数据框,然后将它们分开

Combine 2 dataframe and then separate them

我有 2 个具有相同列的数据框 headers。我希望对它们都进行热编码。我不能一一表演。我希望将两个数据帧附加在一起,然后执行热编码,然后将它们分成 2 个数据帧,每个数据帧再次 headers。

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

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

使用带键的 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)

输出:

#Train 
  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

#Test
   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