Append column to pandas dataframe

Viewed 434024

This is probably easy, but I have the following data:

In data frame 1:

index dat1
0     9
1     5

In data frame 2:

index dat2
0     7
1     6

I want a data frame with the following form:

index dat1  dat2
0     9     7
1     5     6

I've tried using the append method, but I get a cross join (i.e. cartesian product).

What's the right way to do this?

6 Answers

You can assign a new column. Use indices to align correspoding rows:

df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 20, 30]}, index=[0, 1, 2])
df2 = pd.DataFrame({'C': [100, 200, 300]}, index=[1, 2, 3])

df1['C'] = df2['C']

Result:

   A   B      C
0  1  10    NaN
1  2  20  100.0
2  3  30  200.0

Ignore indices:

df1['C'] = df2['C'].reset_index(drop=True)

Result:

   A   B    C
0  1  10  100
1  2  20  200
2  3  30  300

Perhaps too simple by anyways...

dat1 = pd.DataFrame({'dat1': [9,5]})
dat2 = pd.DataFrame({'dat2': [7,6]})
dat1['dat2'] = dat2  # Uses indices from dat1

Result:

    dat1  dat2
0     9     7
1     5     6
Related