bongbang
bongbang

Reputation: 1712

Assign multiple rows & columns from one Pandas dataframe to another

What's the canonical way to do it? The most obvious syntaxes to me don't work. It's as if Pandas were trying to the whole dataframe to each of the relevant elements.

foo = pd.DataFrame(np.zeros((5,2), dtype=int), columns=['a','b'])
foo2 = foo.copy()
bar = pd.DataFrame([[1,2], [3,4]], index=[1,3], columns=['c','d'])

foo.loc[bar.index,['a','b']] = bar.loc[:,['c','d']] 
# same result for foo.loc[bar.index, :] = bar   
print(foo)

Produces:

     a    b
0  0.0  0.0
1  NaN  NaN
2  0.0  0.0
3  NaN  NaN
4  0.0  0.0

You can, however, make the assignment one series at a time, which requires a loop.

for (foo_col, bar_col) in zip(foo2.columns, bar.columns):
    foo2.loc[bar.index, foo_col] = bar[bar_col]

print(foo2)  

Produces:

   a  b
0  0  0
1  1  2
2  0  0
3  3  4
4  0  0

Upvotes: 0

Views: 384

Answers (1)

BENY
BENY

Reputation: 323326

Using update

foo = pd.DataFrame(np.zeros((5,2), dtype=int), columns=['a','b'])
bar = pd.DataFrame([[1,2], [3,4]], index=[1,3], columns=['c','d'])

foo.update(bar.rename(columns=dict(zip(bar.columns,foo.columns))))
foo
Out[51]: 
     a    b
0  0.0  0.0
1  1.0  2.0
2  0.0  0.0
3  3.0  4.0
4  0.0  0.0

Upvotes: 3

Related Questions