-1

I have two Dataframe like those:

| A  | B  |     | C  | D  |
| A1 | B2 |     | C2 | D2 |
| A1 | B3 |     | C1 | D2 |
| A2 | B2 |     | C1 | D3 |

And I need to append every row from B to each row of A, like this:

| A  | B  | C  | D  |
| A1 | B2 | C2 | D2 |
| A1 | B2 | C1 | D2 |
| A1 | B2 | C1 | D3 |
| A1 | B3 | C2 | D2 |
| A1 | B3 | C1 | D2 |
| A1 | B3 | C1 | D3 |
| A2 | B2 | C2 | D2 |
| A2 | B2 | C1 | D2 |
| A2 | B2 | C1 | D3 |
  • 3
    please take the [tour], read up on [ask], and revise your question to include a [mcve] showing what you have tried so far, and where you are having problems or errors. – David Zemens Jun 04 '19 at 18:07

1 Answers1

2

Try using a psuedo key and merge:

df1 = pd.DataFrame({'A':['A1','A1','A2'], 'B':['B2','B3','B2']})
df2 = pd.DataFrame({'C':['C2','C1','C1'], 'D':['D2','D2','D3']})

df1.assign(key=1).merge(df2.assign(key=1)).drop('key', axis=1)

Output:

    A   B   C   D
0  A1  B2  C2  D2
1  A1  B2  C1  D2
2  A1  B2  C1  D3
3  A1  B3  C2  D2
4  A1  B3  C1  D2
5  A1  B3  C1  D3
6  A2  B2  C2  D2
7  A2  B2  C1  D2
8  A2  B2  C1  D3
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • 1
    This question was already answered as mentioned above, it worked with the code below: def cartesian_product_basic(df1, df2): return ( df1.assign(key=1).merge(df2.assign(key=1), on='key').drop('key', 1)) – Elton Marques Jun 04 '19 at 18:38