2

Please, given the two dataframes:

DF1:

A B a1 b1 a2 b2 a3 b3 

DF2:

C1 C2 C3 0 0 1 

I would like to do the following DF1+DF2 producing the following:

 A B C1 C2 C3 a1 b1 0 0 1 a2 b2 0 0 1 a3 b3 0 0 1 

it is not clear to me how I should use one of Merge, Join or concatenate. Please, any help would be very appreciated.c.

2

3 Answers 3

5

Let's use some unpacking and forward fill nas:

DF1.assign(**DF2).ffill() 

OR, let's create a dummy key to do a cartesian join, and drop the dummy key.

DF1.assign(key=1).merge(DF2.assign(key=1), on='key').drop('key',axis=1) 

Output:

 A B C1 C2 C3 0 a1 b1 0.0 0.0 1.0 1 a2 b2 0.0 0.0 1.0 2 a3 b3 0.0 0.0 1.0 
Sign up to request clarification or add additional context in comments.

2 Comments

Do not change the name my friend...please :-)
Actually Scott Boston Solved the problem.
4

pd.concat + ffill

pd.concat([df1,df2],1).ffill() Out[1188]: A B C1 C2 C3 0 a1 b1 0.0 0.0 1.0 1 a2 b2 0.0 0.0 1.0 2 a3 b3 0.0 0.0 1.0 

3 Comments

does not solved the problem. It add NaN values. The solution is provided by Scott Boston above.
@CarloAllocca .....what is your problem ? So you do not want any NaN during the calculation ?
Thanks for replying Wen. Yes, the problem was there were some additional NaN values at the first row which I do not want.
1

If df2 contains only one row we can do it this way:

In [30]: df1.assign(**df2.iloc[0].to_dict()) Out[30]: A B C1 C2 C3 0 a1 b1 0 0 1 1 a2 b2 0 0 1 2 a3 b3 0 0 1 

1 Comment

Yeah... I do like that way better it safer with one row.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.