Home > OS >  Pandas - default masks values when indexing conditionally
Pandas - default masks values when indexing conditionally

Time:11-22

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.

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

CodePudding user response:

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 
  • Related