I have two dataframes like the below:
DF1:
| col1 | col2 |
|---|---|
| 22 | yes |
| 22 | no |
| 24 | yes |
| 22 | no |
| 27 | no |
DF2:
| col1 | col2 |
|---|---|
| 28 | yes |
| 22 | no |
| 29 | yes |
| 22 | yes |
| 27 | yes |
I want to concat both dataframes, so that I end up with the below. I don't want to join the dataframes on col1, as that doubles the number of columns. I just want to combine the dataframe vertically if they share a common value on "col1." Any help on this?
DF3:
| col1 | col2 |
|---|---|
| 22 | yes |
| 22 | no |
| 22 | no |
| 22 | no |
| 22 | yes |
| 27 | no |
| 27 | yes |
CodePudding user response:
Let us first find the common values using set intersection then concat the required rows from df1 and df2 and optionally sort the values
i = set(df1['col1']) & set(df2['col1'])
pd.concat([df1[df1['col1'].isin(i)], df2[df2['col1'].isin(i)]]).sort_values('col1')
col1 col2
0 22 yes
1 22 no
3 22 no
1 22 no
3 22 yes
4 27 no
4 27 yes
