0

This may be a very simple solution that I am missing but I want to combine two dataframes, by adding each individual row to every row in another dataframe. Please see the example below.

df:

      name           
 0     ben
 1     john
 2     tom

df1:

      colour
 0     red
 1     blue

result:

         name   colour
     0    ben    red
     1    ben    blue
     2    john   red
     3    john   blue
     4    tom    red
     5    tom    blue
    
     

Seems like it could be a simple solution so apologies. Thanks in advance.

toothsie
  • 245
  • 3
  • 10

2 Answers2

1

This can be done with cross merge:

(df1.assign(dummy=1)
    .merge(df2.assign(dummy=1), on='dummy')
    .drop('dummy', axis=1)
)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

You can use pandas.MultiIndex.from_product:

import pandas as pd
numbers = [0, 1, 2]
colors = ['green', 'purple']
df = pd.DataFrame(index=pd.MultiIndex.from_product([numbers, colors],
                  names=['number', 'color'])).reset_index()
ronkov
  • 1,263
  • 9
  • 14