简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM