This is my dataframe:
d = { 'id':[1,2,3,4,5,6,7,8,9,10],
'col1':['abc','def','ghi','ghi','jkl','mno','mno','pqr','stu','vwx'],
'col2':['ect','qax','vcx','qtr','vcx','vcx','vcx','nhg','fbv','nhg']
}
df = pd.DataFrame(d)
All values in id
are unique, I want to MultiIndex col1
and col2
and get all ids for each combination in col1
and col2
.
This is how I want the result to look, kind of like a pivot table.
Output:
col1 col2 id
abc ect 1
def qax 2
ghi vcx 3
ghi qtr 4
jkl vcx 5
mno vcx 6
7
pqr nhg 8
stu fbv 9
vwx nhg 10
What I tried:
df1 = df.drop_duplicates(['col1','col2'])
print(df)
id col1 col2
1 abc ect
2 def qax
3 ghi vcx
5 jkl vcx
6 mno vcx
8 pqr nhg
9 stu fbv
10 vwx nhg
This gives me all possible combinations between col1
and col2
. But I am losing rows from id column which I need. For eg. I lost row with id=7
, because it was a duplicate.
Since I have all combinations from the previous query , could I do run this to get all rows which have same value in col1
and col2
across df
and df1
:
#This query doesnt work , I am just trying to show what columns to compare and get rows.
df.loc[(df['col1'].isin(df1['col1'])) & (df['col2'].isin(df1['col2']))]
Please let me know if more information is needed.