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
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
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
-
7. 1
-
6. 1
-
10. 2
-
11. 2
-
15. 3
-
12. 3
I want this type of output
Thanks and Regards
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
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
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
-
7. 1
-
6. 1
-
10. 2
-
11. 2
-
15. 3
-
12. 3
I want this type of output
Thanks and Regards