darkpool darkpool - 3 months ago 10
Python Question

Merge dataframes without matching column

I have the following two dataframes:

df1:
column_01 value_01
aaa 1
bbb 2

df2:
column_02 value_02
ccc 3
ddd 4


I need to merge the dataframes such that the rows in
df1
are duplicated to contain a row for every row in
df2
. The output would be as follows:

column_01 value_01 column_02 value_02
aaa 1 ccc 3
aaa 1 ddd 4
bbb 2 ccc 3
bbb 2 ddd 4


I have tried variations of
merge
and
join
, but can't get it working because I am not matching column values, I am purposely trying to duplicate
df1
rows for each
df2
row.

Answer

You can use create new columns with some scalar value and then merge by these columns:

df1['one'] = 1
df2['one'] = 1
print (pd.merge(df1, df2, on='one').drop('one', axis=1))
  column_01  value_01 column_02  value_02
0       aaa         1       ccc         3
1       aaa         1       ddd         4
2       bbb         2       ccc         3
3       bbb         2       ddd         4
Comments