简体   繁体   中英

How to do left join with larger table, keeping left tables size?

I have a dataframe1:

id    val
a1    0
a1    5
a2    3

and dataframe2:

id    type1          type2
a1    main            k
a2    secondary       b
a3    old             k
a4    deleted         n

i want to join type column to dataframe1 by id to get:

id    val   type1          type2
a1    0      main            k
a1    5      main            k
a2    3      secondary       b

How could I do that? as you see output table is same shape as dataframe1? but when i use pd.merge output is larger

Try this:

out = pd.merge(dataframe1, dataframe2, how='inner', on=['id'])

Output:

id    val   type1          type2
a1    0      main            k
a1    5      main            k
a2    3      secondary       b
df = pd.merge(df1, df2)

or

df = df1.merge(df2)

should work just fine.

Output

   id  val      type1 type2
0  a1    0       main     k
1  a1    5       main     k
2  a2    3  secondary     b

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