There is a clean, one-line way of doing this in Pandas:

df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)

This allows f to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the columns.

Example with data (based on original question):

import pandas as pd

df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

Output of print(df):

  ID  col_1  col_2      col_3
0  1      0      1     [a, b]
1  2      2      4  [c, d, e]
2  3      3      5  [d, e, f]

If your column names contain spaces or share a name with an existing dataframe attribute, you can index with square brackets:

df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)
Answer from ajrwhite on Stack Overflow
Top answer
1 of 16
717

There is a clean, one-line way of doing this in Pandas:

df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)

This allows f to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the columns.

Example with data (based on original question):

import pandas as pd

df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

Output of print(df):

  ID  col_1  col_2      col_3
0  1      0      1     [a, b]
1  2      2      4  [c, d, e]
2  3      3      5  [d, e, f]

If your column names contain spaces or share a name with an existing dataframe attribute, you can index with square brackets:

df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)
2 of 16
483

Here's an example using apply on the dataframe, which I am calling with axis = 1.

Note the difference is that instead of trying to pass two values to the function f, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000

In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  

In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000

Depending on your use case, it is sometimes helpful to create a pandas group object, and then use apply on the group.

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.apply.html
pandas.DataFrame.apply — pandas documentation - PyData |
The resulting column names will be the originals. >>> df.apply(lambda x: [1, 2], axis=1, result_type="broadcast") A B 0 1 2 1 1 2 2 1 2 · Advanced users can speed up their code by using a Just-in-time (JIT) compiler with apply. The main JIT compilers available for pandas are Numba and Bodo.
Discussions

Applying function to values in multiple columns in Pandas Dataframe.

As far as the defining columns twice part goes, you should define the ones to be zfilled once and then reference it in both places. Then you can use applymap and ditch one lambda:

zfill_cols = ['Date', 'Departure time', 'Arrival time']
df[zfill_cols] = df[zfill_cols].applymap(lambda s: s.zfill(4))

Or on the entire dataframe:

df = df.applymap(lambda s: s.zfill(4))

EDIT: You can also use DataFrame.apply and Series.str.zfill which is probably faster because it takes advantage of vector functions (unlike Series.apply and DataFrame.applymap:

df[zfill_cols] = df[zfill_cols].apply(lambda se: se.str.zfill(4))

Or

df = df.apply(lambda se: se.str.zfill(4))
More on reddit.com
🌐 r/learnpython
2
5
November 26, 2015
Append multiple columns applying function that use multiple columns as attr (Pandas)
Your function returns a tuple, which you're trying to assign to more than one column (a tuple is a single object). For example, running something like df['c'] = df.apply(lambda x: f(x.a,x.b), axis=1) would return your tuple within one column. If you wanted just the first operation of your function you would grab the first value in the tuple df['c'] = df.apply(lambda x: f(x.a,x.b)[0], axis=1) And if you wanted to assign the output to two columns within one statement, you can just unpack the tuple in your lambda expression by converting the tuple to a Series. df[['c','d']] = df.apply(lambda x: pd.Series(f(x.a,x.b)), axis=1) More on reddit.com
🌐 r/learnpython
3
2
February 26, 2022
python - applying lambda row on multiple columns pandas - Stack Overflow
And creating a column 'col' based on condition of 'target' column >> same as source, if matching condition, else to a default, as below: tp['col'] = tp.apply(lambda row:row['source'] if row['target'] in ['b','n'] else 'x') But it's throwing me this error: KeyError: ('target', 'occurred at index count') How can I make it work, without defining a function? ... You need to use axis=1 to tell Pandas ... More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2021
Feature-Request: Allow lambda function with different columns in transform
Problem description Currently, if you want to create a new column in a Pandas dataframe that is calculated with a custom function and involves multiple columns in the custom function, you have to c... More on github.com
🌐 github.com
3
November 13, 2018
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas apply() function to single & multiple column(s)
Pandas apply() Function to Single & Multiple Column(s) - Spark By {Examples}
December 6, 2024 - # Apply function NumPy.square() ... # A B C #0 9 25 7 #1 4 16 6 #2 25 64 9 ... apply() is a Pandas DataFrame method used to apply a function along the axis of a DataFrame....
🌐
Statology
statology.org › home › pandas: how to apply function to multiple columns
Pandas: How to Apply Function to Multiple Columns
April 19, 2024 - Often you may want to create a function that you can apply to multiple columns in a pandas DataFrame. The easiest way to do this is by using the lambda function inside of the apply() function in pandas.
🌐
ProjectPro
projectpro.io › blog › how to apply lambda functions to python pandas?
How To Apply Lambda Functions To Python Pandas?
October 28, 2024 - For example, you can use the following code to apply a lambda function to a DataFrame to double all the values in the 'Age' column for each row- ... You can apply Lambda functions to multiple rows in Pandas using the .apply() method.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-apply-a-function-to-multiple-columns-in-pandas
How to Apply a function to multiple columns in Pandas? - GeeksforGeeks
July 15, 2025 - # import the module import pandas as pd # creating a DataFrame df = pd.DataFrame({'String 1' :['Tom', 'Nick', 'Krish', 'Jack'], 'String 2' :['Jane', 'John', 'Doe', 'Mohan']}) # function for prepending 'Geek' def prepend_geek(name): return 'Geek ' + name # executing the function df[["String 1", "String 2"]] = df[["String 1", "String 2"]].apply(prepend_geek) # displaying the DataFrame display(df) ... Here, we are multiplying all the columns by 2 by calling the multiply_by_2 function.
Find elsewhere
🌐
Medium
medium.com › @manishsingh7163 › useful-trick-for-data-scientists-using-apply-and-lambda-function-288a583797af
Useful trick for data scientists using apply and lambda function | by Manish Singh | Medium
January 7, 2023 - All you have to do is specify which axis you want to apply the function to (rows or columns) and the function will be applied to each element on that axis. import pandas as pd # Define the lambda function lambda_function = lambda x: x['col1'] ...
🌐
Skytowner
skytowner.com › explore › applying_a_function_that_takes_as_input_multiple_column_values_in_pandas
Applying a function that takes as input multiple column values in Pandas
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 D · 0 2 4 6 10 · 1 3 5 7 12 · Pandas DataFrame | apply method ·
🌐
Medium
codeforests.medium.com › ppicpandas-tricks-pass-multiple-columns-to-lambda-e0c16312fb50
Pandas Tricks — Pass Multiple Columns To Lambda | by codeforests | Jul, 2020 | Medium | Medium
December 15, 2021 - This article will be sharing with you how to pass multiple columns to lambda or self-defined functions when dealing with data using pandas
🌐
Reddit
reddit.com › r/learnpython › append multiple columns applying function that use multiple columns as attr (pandas)
r/learnpython on Reddit: Append multiple columns applying function that use multiple columns as attr (Pandas)
February 26, 2022 -

I have a DataFrame and a function, and I'd like to append 'c', 'd' col using a,b passed into function.

df = pd.DataFrame({
    'a' : [1,2,3],
    'b' : [4,5,6],})

def f(a,b):
    return a+b, a-b

# What I assumed it should work, it did not.
df[['c', 'd']] = df.apply(lambda x: f(x.a, x.b), axis=1)
>>> ValueError: Columns must be same length as key

I know several ways that could make it work but it seems pretty hard-coded. I wonder how is the above not working and if it's possible to fix it, using apply method.

🌐
DataScientYst
datascientyst.com › apply-function-multiple-columns-pandas
How to apply function to multiple columns in Pandas
September 11, 2021 - You can select several columns ... else: return 'no country ' df[['Latitude', 'Longitude', 'Magnitude']].apply(lambda x: geo_rev(*x), axis=1) result of this operation is: 23402 Papua Niugini 5.8 23403 Chile 7.6 23404 Chile ...
🌐
YouTube
youtube.com › watch
Apply Functions to Multiple Columns - Pandas For Machine Learning 16 - YouTube
In this video I'll show you how to use the apply() function in Pandas on multiple columns of a DataFrame.In the last video I showed you what the apply functi...
Published   August 3, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › applying-lambda-functions-to-pandas-dataframe
Applying Lambda functions to Pandas Dataframe - GeeksforGeeks
March 6, 2025 - We can apply a lambda function to both the columns and rows of the Pandas data frame.Syntax: lambda arguments: expressionAn anonymous function which we can pass in instantly wit ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to apply a function to columns in pandas
How To Apply a Function To Columns in Pandas | Towards Data Science
January 20, 2025 - On the other hand, in occasions where you need to apply a certain function over multiple columns, then you should probably use [pandas.DataFrame.apply()](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html) method.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 24267
Feature-Request: Allow lambda function with different columns in transform · Issue #24267 · pandas-dev/pandas
November 13, 2018 - ## This does NOT work at the moment: df['ab_weighted'] = df.groupby('c')[['a', 'b']].transform(lambda df: sum(df.a)/sum(df.b)) ## This works, but does not broadcast the result back to original dataframe length: df.groupby('c')[['a', 'b']].apply(lambda df: sum(df.a)/sum(df.b)) ... commit: None python: 3.6.6.final.0 python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6 Model 61 Stepping 4, GenuineIntel byteorder: little LC_ALL: None LANG: None LOCALE: de_DE.cp1252 · pandas: 0.23.4 pytest: 3.8.0 pip: 10.0.1 setuptools: 40.2.0 Cython: 0.28.5 numpy: 1.15.1 scipy: 1.
Author   harlecin
🌐
Kanoki
kanoki.org › 2022 › 02 › 11 › how-to-return-multiple-columns-using-pandas-apply
How to return multiple columns using pandas apply | kanoki
February 11, 2022 - In this article we are going to compare the performance of two approaches i.e. Apply method and Vectorization which can be used to apply a function on dataframe and return multiple new columns · we will be following the below steps to create those multiple columns for a dataframe using a custom function: Create a dataframe with 10K rows and two columns name and size(bytes) respectively · Build a function to convert the size to Kilobytes(kb), Megabytes(MB) and Gigabytes(GB) Use pandas.Series.apply() to apply the function created in Step#2 above to create three new columns size_kb, size_mb and size_gb respectively
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas apply() with lambda examples
Pandas apply() with Lambda Examples - Spark By {Examples}
August 16, 2022 - pandas.DataFrame.apply() can be used along with the Python lambda function to apply a custom operation to all columns in a DataFrame. A lambda function is