Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda Function Pandas to Set Column Values

Could anyone suggest a way answer the same question (see link) but by using lambda function: Update a dataframe in pandas while iterating row by row

like image 940
MarcCharbo Avatar asked Jun 26 '17 04:06

MarcCharbo


People also ask

How do I use lambda function on a column in Pandas?

Apply Lambda Function to Single Column You can apply the lambda function for a single column in the DataFrame. The following example subtracts every cell value by 2 for column A – df["A"]=df["A"]. apply(lambda x:x-2) . Yields below output.

How lambda function works in Pandas?

We can do this with the apply() function in Pandas. We can use the apply() function to apply the lambda function to both rows and columns of a dataframe. If the axis argument in the apply() function is 0, then the lambda function gets applied to each column, and if 1, then the function gets applied to each row.

How do you change a value in a DataFrame column?

DataFrame. replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame. When inplace=True is used, it replaces on existing DataFrame object and returns None value.

Can a lambda function return a value?

The lambda function above is defined and then immediately called with two arguments ( 2 and 3 ). It returns the value 5 , which is the sum of the arguments.


1 Answers

You'll want to use apply with the parameter axis=1 to insure the function passed to apply is applied to each row.

The referenced question has an answer that uses this loop.

for i, row in df.iterrows():
    if <something>:
        row['ifor'] = x
    else:
        row['ifor'] = y

    df.ix[i]['ifor'] = x

To use a lambda with the same logic

df['ifor'] = df.apply(lambda row: x if something else y, axis=1)
like image 69
piRSquared Avatar answered Oct 19 '22 03:10

piRSquared