Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two or more columns values only if another column value is True

How would you compare two (or more columns) values ONLY if another column value is True. Ideally, the output would just be True(if everything is matching correctly) False otherwise.

Something like that: df['value1'].equals(df['value2']) but only if df['isValid'] is true.

Sorry if this is a stupid question, I am a beginner with panda...

Consider the below Dataframe:

Example1:

isValid     value1   value2
True        50       50
True        19       19
False       48       40

Output should be: True as record one and two matches and the "isValid" column is True (meaning we have to compare the values)

Example2:

isValid     value1   value2
False       50       50
False       19       19
False       48       40

Output should be True (no comparison to do, nothing wrong then)

Example3:

isValid     value1   value2
True        50       50
False       19       19
True        48       40

Output should be False (because record 3 has value1 and value2 different)

like image 776
WilliamW Avatar asked Nov 14 '19 16:11

WilliamW


People also ask

How do I compare two columns in Excel based on conditions?

Navigate to the "Home" option and select duplicate values in the toolbar. Next, navigate to Conditional Formatting in Excel Option. A new window will appear on the screen with options to select "Duplicate" and "Unique" values. You can compare the two columns with matching values or unique values.

How do I compare two cells in Excel to return true or false?

The quickest way to compare two cells is with a formula that uses the equal sign. If the contents of cell A2 and cell B2 are the same, the result is TRUE. Note: Upper and lower case versions of the same letter are treated as equal, as you can see in the screen shot below.

Can Vlookup match multiple columns?

VLOOKUP doesn't handle multiple columns. In the following example, if we wanted to find the match for both Movie and Showtime column, it wouldn't be possible with basic VLOOKUP syntax.


2 Answers

I will do

df.eval('value1==value2')[df.isValid].all()
like image 186
BENY Avatar answered Nov 04 '22 11:11

BENY


here is a way:

df1[df1['isValid']].set_index('isValid').nunique(1).eq(1).all().all()
#True
like image 3
anky Avatar answered Nov 04 '22 12:11

anky