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.

🌐
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.
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
October 14, 2017
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
June 27, 2022
python - How to apply lambda function on multiple columns using pandas - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
pandas - Python apply lambda with multiple columns - Stack Overflow
CopyKeyError Traceback (most recent ... 1>() ----> 1 df.apply(lambda x: x['B'] if x['A'].isin([1,2,3,4,5]) else x['C']) File c:\Anaconda\envs\xxxxx\xxxx.py:8839, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs) 8828 from pandas.core.apply import frame_apply ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ... In Pandas, applying lambda functions to multiple columns streamlines data transformations across various parts of a DataFrame....
🌐
Medium
theitken.medium.com › ppicpandas-tricks-pass-multiple-columns-to-lambda-e0c16312fb50
Pandas Tricks — Pass Multiple Columns To Lambda | by codeforests | Jul, 2020 | Medium | Medium
July 25, 2020 - Pandas is one of the most powerful tool for analyzing and manipulating data. In this article, I will be sharing with you the solutions for a very common issues you might have been facing with pandas when dealing with your data — how to pass multiple columns to lambda or self-defined functions.
🌐
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'] ...
🌐
Delft Stack
delftstack.com › home › howto › python pandas › pandas apply multiple columns
How to Apply a Function to Multiple Columns in Pandas DataFrame | Delft Stack
February 2, 2024 - import pandas as pd import numpy as np df = pd.DataFrame( [[5, 6, 7, 8], [1, 9, 12, 14], [4, 8, 10, 6]], columns=["a", "b", "c", "d"] ) print("The original dataframe:") print(df) df["e"] = df.apply(lambda x: x.a + x.b, axis=1) print("The new dataframe:") print(df)
Find elsewhere
🌐
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.
🌐
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)
June 27, 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 ...
🌐
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.
🌐
Pandasdataframe
pandasdataframe.com › pandas-apply-lambda-multiple-columns.html
Pandas Apply Lambda on Multiple Columns-Pandas Dataframe
Let’s start with a simple example where we use apply() and a lambda function to add two columns of a DataFrame. import pandas as pd # Create a DataFrame data = { 'A': [1, 2, 3], 'B': [4, 5, 6] } df = pd.DataFrame(data) # Use apply() with a lambda function to add two columns df['C'] = ...
🌐
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 - Using Pandas.DataFrame.apply() method you can execute a function to a single column, all, and a list of multiple columns (two or more). In this article, I
🌐
GeeksforGeeks
geeksforgeeks.org › applying-lambda-functions-to-pandas-dataframe
Applying Lambda functions to Pandas Dataframe - GeeksforGeeks
August 9, 2024 - In Python Pandas, we have the freedom to add different functions whenever needed like lambda function, sort function, etc. We can apply a lambda function to both the columns and rows of the Pandas data frame.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.apply.html
pandas.DataFrame.apply — pandas 3.0.6 documentation
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.
🌐
Zerve
zerve.ai › data-science-problems › pandas › apply-function-multiple-columns-pandas
How to Apply Function to Multiple Columns in Pandas
import pandas as pd import numpy ... same transformation to multiple columns cols = ['a', 'b', 'c'] df[cols] = df[cols].apply(lambda x: x * 2) # ✅ Element-wise function with applymap (deprecated in...