JOHN
JOHN

Reputation: 1511

Why my code works (filtering a data-frame with a function)?

First of all, I have created a function with input of lat Lon in order to filter ships not entering a particular zone.

check_devaiation_notInZone(LAT, LON)

It takes two inputs and return True if ships not enter a particular zone.

Secondly, I got data on many ships with Lat in one header and Lon in another header in CSV format. So, I need to take data from two column into the function and create another column to store the output of the function.

After I looked at Pandas: How to use apply function to multiple columns. I found the solution df1['deviation'] = df1.apply(lambda row: check_devaiation_notInZone(row['Latitude'], row['Longitude']), axis = 1)

But I have no idea why it works. Can anyone explain the things inside the apply()?

Upvotes: 1

Views: 42

Answers (1)

mrCarnivore
mrCarnivore

Reputation: 5078

A lambda function is just like a normal function but it has no name and can be used only in the place where it is defined.

lambda row: check_devaiation_notInZone(row['Latitude'], row['Longitude'])

is the same as:

def anyname(row):
    return check_devaiation_notInZone(row['Latitude'], row['Longitude'])

So in the apply you just call another function check_devaiation_notInZone with the parameters row['Latitude'], row['Longitude'].

Upvotes: 1

Related Questions