EN VI

Use python to compare the values ​in two fields to find the same value?

2024-03-11 15:30:04
How to Use python to compare the values ​in two fields to find the same value?

this is my CODE

import pandas as pd
data1 = {'A': [1, 1, 2, 3, 4, 4, 2, 1], 'B': [2, 2, 3, 4, 4, 4, 1, 2]}
df1 = pd.DataFrame(data1)
df1['OUTPUT'] = df1.duplicated(subset=['A', 'B'], keep=False).map({True: 'OK', False: 'NG'})
print(df1)

and the output is this,but is not i want

enter image description here

i want the output is

enter image description here

update: Sorry, this was my mistake. The values ​​in A and B are strings, not numbers.

Solution:

If need compare values without order use sorted or frozenset in DataFrame.apply:

df1['OUTPUT'] = (df1[['A', 'B']].apply(sorted, axis=1).duplicated(keep=False)
                                .map({True: 'OK', False: 'NG'}))
print(df1)
   A  B OUTPUT
0  1  2     OK
1  1  2     OK
2  2  3     NG
3  3  4     NG
4  4  4     OK
5  4  4     OK
6  2  1     OK
7  1  2     OK

Or use np.sort:

df1['OUTPUT'] = (pd.DataFrame(np.sort(df1[['A', 'B']], axis=1), 
                              index=df1.index).duplicated(keep=False)
                                              .map({True: 'OK', False: 'NG'}))
print(df1)
   A  B OUTPUT
0  1  2     OK
1  1  2     OK
2  2  3     NG
3  3  4     NG
4  4  4     OK
5  4  4     OK
6  2  1     OK
7  1  2     OK

If need compare next with previous rows without ordering compare Series.shifted values in helper Series:

s = df1[['A', 'B']].apply(sorted, axis=1)

df1['OUTPUT'] = (s.eq(s.shift()) | s.eq(s.shift(-1))).map({True: 'OK', False: 'NG'})
print(df1)
   A  B OUTPUT
0  1  2     OK
1  1  2     OK
2  2  3     NG
3  3  4     NG
4  4  4     OK
5  4  4     OK
6  2  1     OK
7  1  2     OK
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login