Sometimes, we want to apply a function to two columns of Pandas DataFrame in Python.
In this article, we’ll look at how to apply a function to two columns of Pandas DataFrame in Python.
How to apply a function to two columns of Pandas DataFrame in Python?
To apply a function to two columns of Pandas DataFrame in Python, we can use the DataFrame’s apply method.
For instance, we write:
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)
print(df)
We frame the df DataFrame with some data in it.
And we have the mylist list that we want to add to DataFrame as another column.
Next, we create the get_sublist function that returns a slice of mylist.
Then we call df.apply with a function that calls get_sublist with the start and end indexes and set that as the value of the col_3 column of the DataFrame.
Therefore, df is:
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]
Conclusion
To apply a function to two columns of Pandas DataFrame in Python, we can use the DataFrame’s apply method.