Home > Software engineering >  How to do left join with larger table, keeping left tables size?
How to do left join with larger table, keeping left tables size?

Time:08-16

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

CodePudding user response:

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

CodePudding user response:

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
  • Related