2

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.

1 Answer 1

1

You can use:

df1=df.copy() 
df1[['col1','col2']]=df[['col1','col2']].mask(df.drop('id',1).duplicated(),'')
df
   id col1 col2
0   1  abc  ect
1   2  def  qax
2   3  ghi  vcx
3   4  ghi  qtr
4   5  jkl  vcx
5   6  mno  vcx
6   7          
7   8  pqr  nhg
8   9  stu  fbv
9  10  vwx  nhg

Or maybe

df1=df.set_index(['col1','col2'])
           id
col1 col2    
abc  ect    1
def  qax    2
ghi  vcx    3
     qtr    4
jkl  vcx    5
mno  vcx    6
            7
pqr  nhg    8
stu  fbv    9
vwx  nhg   10
1
  • I am not able to search value after converting col1 as index. Is there a way to do that? df1.loc[df1['col1'] == 'ghi'] Commented May 20, 2020 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.