2

I am working with an adult dataset where I split the dataframe to label encode categorical columns. Now I want to append the new dataframe with the original dataframe. What is the simplest way to perform the same?

Original Dataframe-

age salary
32 3000
25 2300

After label encoding few columns

country gender
1 1
4 2

I want to append the above dataframe and the final result should be the following.

age salary country gender
32 3000 1 1
25 2300 4 2

Any insights are helpful.

RasK
  • 51
  • 6

3 Answers3

0

You maybe find your solution in checking pandas.concat.

import numpy as np
import pandas as pd

df1 = pd.DataFrame(np.array([[32,3000],[25,2300]]), columns=['age', 'salary'])
df2 = pd.DataFrame(np.array([[1,1],[4,2]]), columns=['country', 'gender'])

pd.concat([df1, df2], axis=1)
         age  salary  country   gender
    0     32      25        1        1
    1   3000    2300        4        2
Pascal
  • 812
  • 7
  • 19
0

lets consider two dataframe named as df1 and df2 hence,

df1.merge(df2,left_index=True, right_index=True)
Deven Ramani
  • 751
  • 4
  • 10
0

You can use .join() if the datrframes rows are matched by index, as follows:

.join() is a left join by default and join by index by default.

df1.join(df2)

In addition to simple syntax, it has the extra advantage that when you put your master/original dataframe on the left, left join ensures that the dataframe indexes of the master are retained in the result.

Result:

   age  salary  country  gender
0   32    3000        1       1
1   25    2300        4       2
SeaBean
  • 22,547
  • 3
  • 13
  • 25