1

I have two tables as follow: Table 1:

Type
ABC
DEF

Table 2:

Date
12/1/2019
1/1/2020
2/1/2020

I'd like to populate a new DataFrame with all the possible combinations like this:

Type    Date
ABC 12/1/2019
ABC 1/1/2020
ABC 2/1/2020
DEF 12/1/2019
DEF 1/1/2020
DEF 2/1/2020
Rich
  • 271
  • 1
  • 13

2 Answers2

4

Looks like you want the cartesian product of both columns here. One way is using pd.MultiIndex.from_product, which creates a MultiIndex from the cartesian product of multiple iterables and construct a dataframe from the indices:

index = pd.MultiIndex.from_product([df1.Type.values, df2.Date.values], 
                                   names = ["Type", "Date"])
pd.DataFrame(index = index).reset_index()

  Type       Date
0  ABC  12/1/2019
1  ABC   1/1/2020
2  ABC   2/1/2020
3  DEF  12/1/2019
4  DEF   1/1/2020
5  DEF   2/1/2020
yatu
  • 86,083
  • 12
  • 84
  • 139
1

A simple merge would do. The trick is to create a dummy column (say key) to join the two dataframe (similar to join in SQL).

Demo:

import pandas as pd
type_df = pd.DataFrame({'Type': ['ABC', 'DEF']})
date_df = pd.DataFrame({'Date': ['12/1/2019', '1/1/2020','2/1/2020']})
type_df['key'] = 0
date_df['key'] = 0
combo = type_df.merge(date_df, how='left', on = 'key')
combo.drop('key', 1, inplace=True)
combo

Result:

    Type    Date
0   ABC 12/1/2019
1   ABC 1/1/2020
2   ABC 2/1/2020
3   DEF 12/1/2019
4   DEF 1/1/2020
5   DEF 2/1/2020
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38