How to find if the values in two columns appear in reverse in a pandas dataframe

Question:

I am pretty new to this, but I’m trying to find if the values in column a and column b appear in reverse order or (another way to say it) where the values are swapped, anywhere else in the columns – if so write 1 in column c, if not write 0 in column c.

Expected output:

column_a  column_b  column_c

1. a      b        1
2. b      a        1
3. d      a        0
Asked By: max

||

Answers:

You can using np.sort then pass the result to duplicated

df['New']=pd.DataFrame(np.sort(df[['column_a','column_b']])).duplicated(keep=False).astype(int)
df
Out[1292]: 
  column_a column_b  column_c  New
0        a        b         1    1
1        b        a         1    1
2        d        a         0    0
Answered By: BENY

I’m new to python, and although it helped me a lot. In my data frame lot of duplicate values are there so I want to assign different values in the third column. Can you please help me with that

Column_a, Column_b, New

  1.    7.        1
    
  2.    6.        1
    
  3.   10.       2
    
  4.   11.       2
    
  5.   15.       3
    
  6.   12.       3
    

I want this type of output

Thanks and Regards

Answered By: Manik Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.