Pandas - Attach column to a DataFrame

Viewed 45

I have two dataframes, which for simplicity look like:

 A     B     C     D     E
 1     2     3     4     5
 5     4     3     2     1
 1     3     5     7     9
 9     7     5     3     1

And the second one looks like:

 F
 0
 1
 0
 1

So, both dataframes have the SAME number of rows.

I want to attach column F to the first dataframe:

 A     B     C     D     E     F
 1     2     3     4     5     0
 5     4     3     2     1     1
 1     3     5     7     9     0
 9     7     5     3     1     1

I have already tried various methods such as joins, iloc, adding df['F'] manually, and I don't seem to find an answer. Most of the time I get F added to the dataframe, but with its data filled with NaN (e.g. the lines where the first dataframe was filled, I get NaN in F, and then I get double the number of rows with NaN everywhere, except F, where the data is OK).

2 Answers

It seems you want to add column F to the first dataframe regardless of the index of both dataframes. In that case, just assign through ndarray of column F

df1['F'] = df2['F'].to_numpy()

Out[131]:
   A  B  C  D  E  F
0  1  2  3  4  5  0
1  5  4  3  2  1  1
2  1  3  5  7  9  0
3  9  7  5  3  1  1

You have just to create a new column on the original dataframe assigning the result of the second dataframe:

generating the example

import pandas as pd 
data1 = {"A": [1, 5, 1, 9],
         "B": [2, 4, 3, 7],
         "C": [3, 3, 5, 5],
         "D": [4, 2, 7, 3],
         "E": [5, 1, 9, 1]}

data2 = {"F": [0, 1, 0, 1]}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

#creating the column
df1["F"] = df2.F
df1
>       A   B   C   D   E   F
>   0   1   2   3   4   5   0
>   1   5   4   3   2   1   1
>   2   1   3   5   7   9   0
>   3   9   7   5   3   1   1
Related