Home > Backend Development > Python Tutorial > How Can I Apply a Function Element-Wise to Multiple Pandas DataFrame Columns?

How Can I Apply a Function Element-Wise to Multiple Pandas DataFrame Columns?

Barbara Streisand
Release: 2024-12-04 01:15:10
Original
329 people have browsed it

How Can I Apply a Function Element-Wise to Multiple Pandas DataFrame Columns?

Pandas: Applying Functions to Multiple Columns

Problem:

Given a function and a Pandas DataFrame with multiple columns, how can we apply the function element-wise to each pair of corresponding values in the columns?

Solution:

There is an efficient way to achieve this using Pandas' lambda function and apply method:

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)
Copy after login

This applies the get_sublist function to each row of the DataFrame, using the values in the 'col_1' and 'col_2' columns as inputs. The result is a new column, 'col_3', containing the calculated sublists.

Usage:

Consider the following example:

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

# Apply the function and create a new column
df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

print(df)
Copy after login

Output:

  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']
Copy after login

The above is the detailed content of How Can I Apply a Function Element-Wise to Multiple Pandas DataFrame Columns?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template