Vinay
Vinay

Reputation: 1261

How to write lambda expression in pandas that uses multiple columns and column names?

I want to achieve the following using pandas lambda expressions

  1. find the value in the column whose name is in the column 'ideal_prime_fc'
  2. find the value in the column whose name is in the column 'prime_fc'
  3. find difference and put in a new column 'delta'

dataframe

Upvotes: 1

Views: 175

Answers (1)

Wes Doyle
Wes Doyle

Reputation: 2287

Would something like the following work for you?

Write a function to subtract the values in the two prime values columns:

def get_col_name(x):
    try:
        ip_fc = x['ideal_prime_fc']
        p_fc = x['prime_fc']
        return x[ip_fc]-x[p_fc]
    except IndexError:
        return float('NaN')  # handle non-existent values however you'd prefer

Apply the function, assigning to a new column:

df['diff'] = df.apply(lambda x: get_col_name(x), axis=1)

A truncated example output:

983     976     ideal_prime_fc  prime_fc    diff
2835    780     973             805         NaN
8       2259    983             983         0.0
2851    796     973             805         NaN
13      7       983             976         6.0   # added for test

Upvotes: 1

Related Questions