1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

No. For example, in the row 0, ideal_prime_fc = 973 and prime_fc = 805. I want to search 805 and 973 in column names and find the difference df.iloc[0]['973'] - df.iloc[0]['805']
@Vinay I've updated my answer based on your clarification
Glad to hear, please accept answer if you have a chance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.