search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

Applying a function that takes as input multiple column values in Pandas

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

To apply a function that takes as input multiple column values, use the DataFrame's `apply(~)` method.

Consider the following DataFrame:

``` df = pd.DataFrame({"A":[2,3],"B":[4,5],"C":[6,7]})df A B C0 2 4 61 3 5 7 ```

Solution

To create a new column called `D` based on some function of columns `B` and `C`:

``` def foo(row): return row["B"] + row["C"]df["D"] = df.apply(foo, axis=1)df A B C D0 2 4 6 101 3 5 7 12 ```

Here, note the following:

• we've defined a custom function called `foo`, which takes as input a single row of type `Series`, and returns the sum of column values `B` and `C`.

• since `row` is a `Series`, we can access the values corresponding to columns `B` and `C` using `[]` notation.

• `axis=1` indicates that we want to pass a row rather than a column to `foo`.

• `foo` is executed for every row in our DataFrame (so twice in this case).

Our solution could be simplified to a compact one-liner using lambdas:

``` df["D"] = df.apply(lambda row: row["B"] + row["C"], axis=1)df A B C D0 2 4 6 101 3 5 7 12 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
3
thumb_down
2
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!