Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – default masks values when indexing conditionally

I have a function which provides the index of the rows which satisfy some given condition (or a series of conditions).

def some_function(df, a, b, c, d):
  return df.index[df["A"].eq(a) & df["B"].eq(b) & df["C"].eq(c) & df.eq(d)]

Now I want to ignore specific conditions if a value is not present.

df.index[df["A"].eq(a) & df["B"].eq(b) & df["C"].eq(c) & (df["D"] if D == None else df["D"].eq(d)]

However, the above condition always returns an empty list.
It seems as the lack of a condition evaluation in df["D"] interferes with the final result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible to conditionally evaluate a condition using Pandas (without writing two separate queries)? If so, how can I do it?

>Solution :

You can create the first part of the mask in a variable, and then update the mask using simple if statements:

def some_function(df, a, b, c, d):
  mask = df["A"].eq(a) & df["B"].eq(b) & df["C"].eq(c)
  if d != None:
    mask &= df["D"].eq(d)
  return df.index[mask]

You also might be use your original attempt, only instead of df["D"] if ... use True if ...:

def some_function(df, a, b, c, d):
  return df.index[df["A"].eq(a) & df["B"].eq(b) & df["C"].eq(c) & (True if d == None else df["D"].eq(d))]
  #                                                                ^^^^ Replaced df["D"] with True 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading