1

I want to merge two dataframes together to mimic 'select * from A, B', for example, table A will look like this:

import pandas as pd
table_a = pd.DataFrame({'id': ['A', 'B']})

table B will look like this:

import pandas as pd
table_b = pd.DataFrame({'x': [1,2], 'y':[3,4]})

What I want to have is

import pandas as pd
table_c = pd.DataFrame({'id':['A', 'A', 'B', 'B'],
                        'x': [1,2,1,2], 'y':[3,4,3,4]})

i.e. duplicate A and B table_b.shape[0] times and append it.

I believe there are multiple ways to do it. For example,

a = table_b.loc[np.tile(table_b.index.values, table_a.shape[0])]
b = table_a.loc[np.repeat(table_a.index.values, table_b.shape[0])]
a['id'] = b['id'].values

Is there any other better way to do this? Thanks

C. Tanaka
  • 145
  • 1
  • 9

1 Answers1

1
pd.DataFrame([
    d1 + d2
    for d1 in zip(*map(table_a.get, table_a))
    for d2 in zip(*map(table_b.get, table_b))
], columns=table_a.columns.append(table_b.columns))
Tom Ron
  • 5,906
  • 3
  • 22
  • 38