Skip to content
Advertisement

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement