user1424739
user1424739

Reputation: 13775

How to add one dataframe to another inplace?

The following code would not add df2 into df1. Note that I must use a function f here.

>>> import pandas
>>> df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
>>> df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
>>> def f(df1, df2):
...     df1 = pandas.concat([df1, df2], axis=1)
...
>>> f(df1, df2)
>>> print(df1)
   A   B
0  1  11
1  2  12
2  3  13

Could anybody let me know the most succinct way to modify df1 as an argument of f in function f so that it will have all the columns in df2 added to it?

Upvotes: 1

Views: 220

Answers (2)

user1424739
user1424739

Reputation: 13775

It seems that this is the most succinct code for this problem.

>>> import pandas
>>> df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
>>> df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
>>> def f(df1, df2):
...     df1[df2.columns] = df2
...
>>> f(df1, df2)
>>> print(df1)
   A   B  C   D
0  1  11  1  11
1  2  12  2  12
2  3  13  3  13

Upvotes: 2

nbk
nbk

Reputation: 49410

In your function you create the joined dataframe, but it is only a local variable

So you can do following

import pandas
df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
def f(df1, df2):
   df1 = pandas.concat([df1, df2], axis=1)
   return df1
df1 = f(df1,df2)
print(df1)

When you want a global variable to be used you have to rewrite the function

now the function is def f(df1a,df2a), because you can't have the same name for different objects

import pandas
df1 = pandas.DataFrame({'A': [1, 2, 3], 'B': [11, 12, 13]})
df2 = pandas.DataFrame({'C': [1, 2, 3], 'D': [11, 12, 13]})
def f(df1a, df2a):
    global df1
    df1 = pandas.concat([df1a, df2a], axis=1)

f(df1,df2)
print(df1)

Output

   A   B  C   D
0  1  11  1  11
1  2  12  2  12
2  3  13  3  13

Upvotes: 1

Related Questions