2

I'm trying to remove duplicate elements in column 'p1' and 'p2' i.e should the elements already occurred in column 'p1' it should not reappear in 'p2' or any subsequent column. For eg, for the code below, only 'a b' and 'c d' will remain.

Whats the effecient way of doing this?

import pandas as pd
df = pd.DataFrame({'p1':['a','b','a','a','b','d','c'],
                'p2':['b','a','c','d','c','a','d'],
                'value':[1,1,2,3,5,3,5]})
df

2 Answers 2

1

You can first set_index from column value, stack for creating Series, drop_duplicates, unstack and last reset_index:

print df.set_index('value').stack().drop_duplicates().unstack().reset_index()
   value    p1 p2
0      1     a  b
1      2  None  c
2      3  None  d
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Jezrael, maybe let me rephrase my question, p1 and p2 got to be a pair. However, whatever already happen in any of my p1 or p2, i do not wish the item to reappear in any of my subsequent p1 or p2
IIUC you need print df.drop_duplicates(subset=['p1','p2']) ?
Maybe understand - you need remove all rows in output df with None values?
I would like to drop the row if p1 duplicate in p2. what's the efficient way of doing it?
Desired output is print pd.DataFrame({'p2': {1: 'a', 4: 'c'}, 'p1': {1: 'b', 4: 'b'}, 'value': {1: 1, 4: 5}}) ?
|
0

Series( pd.DataFrame({'p1':['a','b','a','a','b','d','c'],'p2':['b','a','c','d','c','a','d'],'value':[1,1,2,3,5,3,5]}).values.ravel()).unique()

I'll post output as soon as I get pandas installed in my virtualenv.

1 Comment

But OP wants remove duplicates only from p1 and p2. Next problem is lost index, if df is created by constructor.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.