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

如何使用DataFrame.pct_change并保留原DataFrame所有列?

解决方案
  • 直接给原DataFrame新增列并赋值pct_change的结果,一行代码就能完成,完全保留原有列:

    CH1['Area_SqM_pct_change'] = CH1['Area_SqM'].pct_change()
    

    这种方式本质就是原地修改原DataFrame,无需额外合并操作,比事后合并高效得多。

  • 关于inplace=True:pct_change方法确实没有inplace参数,所以无法使用类似CH1['Area_SqM'].pct_change(inplace=True)的写法,直接新增列是pandas的常规操作方式。

  • 批量处理多表格的优化:如果需要遍历大量DataFrame,可以封装一个简单函数来重复执行操作:

    def add_pct_change(df, target_col, new_col=None):
        # 自定义新列名,默认在原列名后加_pct_change
        if new_col is None:
            new_col = f"{target_col}_pct_change"
        df[new_col] = df[target_col].pct_change()
        return df
    

    遍历时直接调用即可:

    # 假设df_list是你的DataFrame列表
    for df in df_list:
        add_pct_change(df, 'Area_SqM')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:30:50