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

如何将DataFrame apply lambda返回的多值结果追加至原DataFrame或新Series?

解决Pandas apply返回多值时合并为单列的问题

你遇到的问题很常见——当apply调用的函数返回元组时,Pandas默认会把整个元组当作单个元素存入Series的每一行,所以你看到的是一列包含元组的结果,而不是拆分后的多列数据。下面给你两种简单的解决方案,不管是生成新的DataFrame还是追加到原数据里都能搞定:

方法1:让自定义函数返回Series

修改你的mytest函数,让它返回一个带列名的Series,这样apply会自动把Series的每个元素拆分成单独的列:

import pandas as pd

def mytest(row):
    timestamp = row['timestamp']
    wicketsPerOver = row['wickets']/row['overs']
    runsPerWicket = row['runs']/row['wickets']
    # 返回带索引(列名)的Series
    return pd.Series(
        [timestamp, wicketsPerOver, runsPerWicket],
        index=['timestamp_new', 'wickets_per_over', 'runs_per_wicket']
    )

# 调用apply,直接得到多列的DataFrame
stats_df = matchData.apply(lambda row: mytest(row), axis=1)

# 追加到原DataFrame
new_matchData = pd.concat([matchData, stats_df], axis=1)

方法2:使用result_type='expand'参数

如果你不想修改原函数,只需要在apply时加上result_type='expand'参数,就能让Pandas自动把元组的每个元素拆分成单独的列,之后再给列命名即可:

# 调用apply并展开结果
stats_df = matchData.apply(lambda row: mytest(row), axis=1, result_type='expand')

# 给新列命名
stats_df.columns = ['timestamp_new', 'wickets_per_over', 'runs_per_wicket']

# 合并到原DataFrame
new_matchData = pd.concat([matchData, stats_df], axis=1)

小提示

如果你的数据里wickets或overs存在0值,除法会触发ZeroDivisionError,可以提前处理这些情况(比如用try-except或者np.where设置默认值)。

内容的提问来源于stack exchange,提问作者Mike Mavor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:48:08