Home > Software engineering >  how to join 2 rows based on column value
how to join 2 rows based on column value

Time:03-07

i have the dataframe like picture below: enter image description here

and based on col_3 value i want to extract this dataframe.

enter image description here i tried :

df1 = df[df['col_8'] == 2]
df2 = df[df['col_8'] == 3]
df3 = pd.merge(df1, df2, on=['col_3'],  how = 'inner')

but because i have just one col_3=252 after the merge this row is deleted. how can i fix the problem and with which function i can extract above dataframe?

CodePudding user response:

What are you trying to do? In your picture, col_3 only has values of 2 and 3. And then, you split the dataframe on the condition of col_3 = 2 or 3. And then you want to merge it. So, you are trying to slice a dataframe and the rejoin it as it was? Why?

CodePudding user response:

I think this is happening due to your df2 being empty, since there is no df[df['col_8'] == 3]. Inner join is the intersection of the sets. So Df2 is empty so then you try and then you try and merge this it will return nothing.

I think you are trying to do this:

df2 = df[df['col_8_3'] == 3]

Then when you take the inner join it should work produce one row

  • Related