Home > Software engineering >  Pandas: Pass multiple values in a row to a function and replace a value based on the result
Pandas: Pass multiple values in a row to a function and replace a value based on the result

Time:07-25

My original code looks like this. I passed a value in the row to a function and replaced a value based on the result.

m = df["value_a"].isin( a_list)
df.loc[m, "value_b"] = df.loc[m, "value_a"].apply(lambda x: get_new_value_b(arg1, x))

And now I need to pass multiple values in a row to the function. When I pass the values like below, seems like the value is the entire column, not the value in a row.

df.loc[m, "value_b"] = df.loc[m, ["value_a", "value_c"]].apply(lambda x: get_new_value_b(arg1, x))

...

def get_new_value_b(arg1, x):
    print("x: {x}".format(x=x))
    ...


# x: 
# 0    ...
# 1    ...
# ...
# value_a, dtype: object

How can I pass two values (value_a and value_c) to the function properly here?

CodePudding user response:

You can use axis=1 of DataFrame.apply

df.loc[m, "value_b"] = df.loc[m, ["value_a", "value_c"]].apply(lambda row: get_new_value_b(arg1, row), axis=1)

Then access the row value in get_new_value_b with row['col']

  • Related