You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:54:18