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

如何结合map函数生成并合并多个pd.DataFrame?

如何用map函数调用返回DataFrame的函数并合并结果?

你完全可以用map函数实现这个需求,核心是直接把map返回的迭代器传给pd.concat(),而不是pd.DataFrame()。

问题原因

你之前尝试的pd.DataFrame(map(z_score, ['x', 'y']))无法运行,是因为pd.DataFrame的构造函数不支持接收包含DataFrame对象的迭代器作为输入,而pd.concat()专门用于合并多个DataFrame,它可以直接处理迭代器类型的输入。

正确实现代码

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x' : np.random.chisquare(df = 2, size = 10),
    'y' : np.random.chisquare(df = 5, size = 10)    
})

def z_score(x):
    z = (np.mean(df[x]) - df[x]) / np.std(df[x])
    mean_ctr = np.mean(df[x]) - df[x]
    out = pd.DataFrame({
        'z': z,
        'mean_ctr': mean_ctr,
        'var' : x
        })
    return out

# 用map+pd.concat实现合并
final_df = pd.concat(map(z_score, ['x', 'y']))
# 如果需要重置合并后的索引,添加ignore_index=True
# final_df = pd.concat(map(z_score, ['x', 'y']), ignore_index=True)

说明

  • map(z_score, ['x', 'y'])会生成一个迭代器,每次迭代都会返回对应列计算后的小DataFrame
  • pd.concat()会遍历这个迭代器,自动将所有小DataFrame按行拼接成一个大DataFrame,效果和你手动传入列表[z_score('x'), z_score('y')]完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:49:52