Python:在DataFrame列上应用函数并生成两个新列的实现方法
Hey there! Let's get this sorted out. You want to apply your function f(a,b) to columns A and B of your DataFrame, then split the returned tuple into two new columns. Here's how to do it step by step:
Step 1: Set up your initial DataFrame and function
First, let's replicate your starting data and function in code:
import pandas as pd # Your original DataFrame df = pd.DataFrame({ 'A': [5, 4, 7], 'B': [3, 2, 1] }) # The function f(a,b) that returns sum and difference def f(a, b): return (a + b, a - b)
Step 2: Apply the function and create new columns
We'll use df.apply() to run the function row-by-row, then unpack the tuple results into columns C and D. Here are two reliable methods:
Method 1: Expand tuples with pd.Series
This converts each tuple from f into a Series, which pandas automatically maps to new columns:
# Apply the function and assign to new columns C and D df[['C', 'D']] = df.apply(lambda row: pd.Series(f(row['A'], row['B'])), axis=1)
Method 2: Unpack directly with zip(*)
This is more efficient for larger datasets, as it skips intermediate Series objects:
# Unpack the tuple results straight into columns C and D df['C'], df['D'] = zip(*df.apply(lambda x: f(x['A'], x['B']), axis=1))
Result
After running either method, your DataFrame will match exactly what you wanted:
A B C D 0 5 3 8 2 1 4 2 6 2 2 7 1 8 6
Both approaches work great—pick the one that feels most readable to you!
内容的提问来源于stack exchange,提问作者Nastya

