-1

I have a Pandas dataframe. For each row in this frame I want to make a certain check. If the check yields True, then I want to add certain columns of the dataframe-row to a list-structure.

How can I access a list from within the apply function without the need to create a global list variable? Is this possible? Or is there a better way to do this?

The code looks like this:

df.apply(checkFunction, axis=1)

checkFunction(row): 
    if (check == True):
        myList.append(row)
    return row
beta
  • 5,324
  • 15
  • 57
  • 99

1 Answers1

1

df.apply() allows you to pass positional arguments and keywords.

def checkFunction(row, lst): 
    if (check == True):
        lst.append(row)
    return row

my_list = []
df.apply(checkFunction, axis=1, args=(my_list,))

Don't call it list, that collides with the reserved list keyword.

NOTE: The value passed to args must be a tuple. I just edited the sample code to show this.

Craig
  • 4,605
  • 1
  • 18
  • 28