GrayHash
GrayHash

Reputation: 289

pandas: merge help two dataframe

I have a Question in Pandas

two dataframe I want merge.

example)

First DataFrame is here

Year Month Location
 2006  01    NY
 2006  01    CA
 2006  02    CA
 2006  02    NY

and Second DataFrame is here

Type
A
B
C

how can I merge it?

I wanna like this

   Year Month Location Type
   2006  01    NY       A
   2006  01    NY       B
   2006  01    NY       C
   2006  01    CA       A
   2006  01    CA       B
   2006  01    CA       C

Thanks, for your help.

Upvotes: 1

Views: 122

Answers (1)

jezrael
jezrael

Reputation: 863291

You need merge by new columns tmp if need cartesian product. Last drop column tmp:

df1['tmp'] = 1
df2['tmp'] = 1
df = pd.merge(df1,df2, on='tmp').drop('tmp', axis=1)
print (df)
    Year  Month Location Type
0   2006      1       NY    A
1   2006      1       NY    B
2   2006      1       NY    C
3   2006      1       CA    A
4   2006      1       CA    B
5   2006      1       CA    C
6   2006      2       CA    A
7   2006      2       CA    B
8   2006      2       CA    C
9   2006      2       NY    A
10  2006      2       NY    B
11  2006      2       NY    C

Upvotes: 2

Related Questions