I have a large dataframe, let's say 200,000 records.
The dataset looks like:
company id
0 A 123
1 A 124
2 A 135
3 B 124
...
199,997 T 124
199,998 T 632
199,999 T 135
I would like to find all the pairs which have the same id, excluding the company itself. For example, the result should be like:
company_x company_y id_x id_y
0 A B 124 124
1 A T 124 124
2 A T 135 135
...
I know I can simply achieve it by using Cartesian product:
df['a']=1
df2=pd.merge(df,df,how='left',on='a').drop('a',axis=1)
result=df2[(df2['company_x']!=df2['company_y'])&(df2[id_x]==df2[id_y])]
But the problem is the dataframe is too large, using Cartesian product is not a good idea here, which needs a lot of memory.
Is there any better solution?