0

Basically im trying to use a user defined function to calculate values in a row in each dataframe and presenting them to a new column ABCD.

dfx = pd.DataFrame({'A': [1,2,3,4,5], 'B': [10,20,30,40,50], 'C': 
[5,5,5,5,5], 'D' : [2,2,2,2,2]})
print(df)


   A   B  C  D  E(Desired)
0  1  10  5  2
1  2  20  5  2
2  3  30  5  2
3  4  40  5  2
4  5  50  5  2

def functionx(A,B,C,D):
    print( A * B + C / D)



dfx['ABCD'] = functionX

i tried using functionX but it does not work. How do i pass the function correctly through each row and produce a column E which is the result?

1
  • You don't need a function. You can directly apply the formula on the columns with dfx["E"] = dfx.A * dfx.B + dfx.C / dfx.D. However, you want to apply a specific function row per row, have a look at apply Commented Aug 23, 2019 at 9:41

2 Answers 2

2

Add a new column in DataFrame with values based on other columns

You can achieve that by directly performing the required operation on the desired column element-wise:

import pandas as pd

dfx = pd.DataFrame({'A': [1,2,3,4,5], 'B': [10,20,30,40,50], 'C':
[5,5,5,5,5], 'D' : [2,2,2,2,2]})
print(dfx)

dfx['E'] =  dfx['A'] * dfx['B'] + dfx['C'] / dfx['D']
print(dfx)

output:

   A   B  C  D      E
0  1  10  5  2   12.5
1  2  20  5  2   42.5
2  3  30  5  2   92.5
3  4  40  5  2  162.5
4  5  50  5  2  252.5

or you can use DataFrame.apply() function to achieve this task:

dfx['E'] = dfx.apply(lambda row: row.A * row.B + row.C / row.D, axis = 1)

NOTE:

Apply a function along an axis(columns or rows) of the DataFrame:

Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

Sign up to request clarification or add additional context in comments.

Comments

0

Use unpacking with pandas.DataFrame.apply on axis=1:

dfx['E'] = dfx.apply(lambda x: functionx(*x), 1)
print(dfx)

Output:

   A   B  C  D      E
0  1  10  5  2   12.5
1  2  20  5  2   42.5
2  3  30  5  2   92.5
3  4  40  5  2  162.5
4  5  50  5  2  252.5

4 Comments

what does the * inside the function do?
@mohanys it unpacks the iterable, so that one doesn't have to do functionx(x[0], x[1], x[2], x[3]).
oh! was not aware of that, that for the info
@mohanys The document for pep-0448 is about the unpacking. Might be helpful for ya :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.