Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and Concatenate Pandas Dataframe for each row In Another DataFrame

Tags:

python

pandas

I would like to create and stack a dataframe for each row in a different dataframe. For Example

I tried doing this by iterating over the rows of one and copying and stacking the other, but this is a very slow process. Is there a native Pandas way to do this?

like image 382
Maile Cupo Avatar asked Mar 07 '23 00:03

Maile Cupo


1 Answers

Input:

a = pd.DataFrame({'first':[1,2,3],'second':['one','two','three']})
b = pd.DataFrame({'alice':['yes','no'],'bob':['no','yes']})

Create a dummy key and merge creating a cartesian product

a.assign(key=1).merge(b.assign(key=1), on='key').drop('key',axis=1)

Output:

   first second alice  bob
0      1    one   yes   no
1      1    one    no  yes
2      2    two   yes   no
3      2    two    no  yes
4      3  three   yes   no
5      3  three    no  yes
like image 175
Scott Boston Avatar answered Apr 08 '23 09:04

Scott Boston