Vince
Vince

Reputation: 197

How to use 2 argument on the Lambda function with .apply()

Is it possible to make this code faster?

    for i in range (len (data)):
        column_name = data['Name'].values[i]
        if data['Market'].values[i] == 'P':
            market = 'Local'
        else:
            market = 'Oversea'
        data['Momentum'].values[i] = self.Factor_Model (column_name, market)

I am not used to .apply() and lambda functions. Could you guide me how to change above code to like below?

data['Momentum'] = data.apply(lambda row: self.Factor_Model(row['Name'],lambda row: if row['Market'].values == 'P' ))

Thank you for your guide in advance.

Upvotes: 1

Views: 69

Answers (1)

chrisaycock
chrisaycock

Reputation: 37938

I would call .apply() with axis=1 to operate on rows. And then pass each item from the Series to the function directly.

data['Location'] = np.where(data['Market'] == 'P', 'Local', 'Oversea')

data['Momentum'] = data.apply(lambda x: Factor_Model(x['Name'], x['Location']), axis=1)

Upvotes: 1

Related Questions