Combine 2 dataframe and then separate them
Use concat with keys then divide i.e
#Example Dataframes train = pd.DataFrame({'x':[1,2,3,4]})test = pd.DataFrame({'x':[4,2,5,0]})# Concat with keystemp = 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)
Output :
#Train x_0 x_1 x_2 x_3 x_4 x_50 0 1 0 0 0 01 0 0 1 0 0 02 0 0 0 1 0 03 0 0 0 0 1 0#Test x_0 x_1 x_2 x_3 x_4 x_50 0 0 0 0 1 01 0 0 1 0 0 02 0 0 0 0 0 13 1 0 0 0 0 0