0

I have a function to apply to this table

F(x) = 1.5*x1 + 2*x2 - 1.5*x3

Where xi, i = 1,2,3, is the column value.

And I have the following table below.

X1    | X2   | X3
------|------|------
20    |15    |12    
30    |17    |24    
40    |23    |36    

The desired output that I would like is the following below, where I apply the function to each row, taking the value in each column and applying it to the function iteratively then receiving value as a sum and another column appended onto the dataframe.

X1    | X2   | X3   |F(X)
------|------|------|------
20    |15    |12    |42
30    |17    |24    |43
40    |23    |36    |52

Is there a way to do this in Python 2.7?

2 Answers 2

6

Something like this ?

df['F(x)']=df.mul([1.5,2,-1.5]).sum(1)
df
Out[1076]: 
   X1  X2  X3  F(x)
0  20  15  12  42.0
1  30  17  24  43.0
2  40  23  36  52.0
Sign up to request clarification or add additional context in comments.

2 Comments

Welp, that's much shorter than my own answer to this question. Works well too.
Don't forget to approve the answer, don't want to leave mighty @Wen high and dry.
-1

Ok. Found a sample code to solve my problem.

var1 = 1.5
var2 = 2
var3 = -1.5
def calculate_fx(row):
return (var1 * row['X1']) + (var2 * row['X2']) + (var3 * row['X3'])

#function_df is the predefined dataframe
function_df['F(X)'] = function_df.apply(calculate_fx, axis=1)
function_df

Comments

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.