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

如何在Go的gota/dataframe中计算两列差值并生成新列

实现方法

你可以通过Mutate方法结合逐行计算实现需求,先把deposit列的NaN值填充为0,再计算两列差值生成新列,完整代码示例如下:

package main

import (
	"fmt"
	"github.com/go-gota/gota/dataframe"
	"github.com/go-gota/gota/series"
	"os"
)

func main() {
	csvfile, err := os.Open("你的文件路径.csv")
	if err != nil {
		panic(err)
	}
	defer csvfile.Close()
	// 读取CSV
	df := dataframe.ReadCSV(csvfile, dataframe.WithDelimiter(';'))
	// 填充deposit列的NaN为0
	df = df.Mutate(
		series.New(
			df.Col("deposit").Float(),
			series.Float,
			"deposit",
		).Fill(0.0, series.Nil),
	)
	// 计算差值新增列
	df = df.Mutate(
		series.New(
			make([]float64, df.Nrow()),
			series.Float,
			"deposit_Withdrawals_diff",
		).RApply(func(idx int, _ interface{}) interface{} {
			deposit := df.Col("deposit").Float()[idx]
			withdrawal := df.Col("Withdrawals").Float()[idx]
			return deposit - withdrawal
		}),
	)
	// 输出结果
	fmt.Println(df)
}

说明

  • 如果你的deposit和Withdrawals列存储的是整数类型,可以把代码中的Float替换为Int,填充值从0.0改为0即可
  • RApply方法会遍历每一行,通过行索引取对应两列的数值做减法,最终结果会存入新列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:39:03