-3

我正在使用 Go gota/dataframe

我想减去 2 列的值并将其存储到一个新列中。

我搜索了很多但没有运气,请帮助。

   df := dataframe.ReadCSV(csvfile, dataframe.WithDelimiter(';'))
   fmt.println(df)

输出:

   accountId deposit Withdrawals
    anil0001  50      10
    vikas0002 10      10
    ravi0003  20      10
    user1111  NaN     20

我想在新列中区分存款和取款

  accountId deposit Withdrawals deposit_Withdrawals_diff
   anil0001  50      10         40
   vikas0002 10      10         0
   ravi0003  20      10.        10
   user1111  0       20.        -20
4

1 回答 1

1

Gota/dataframe 看起来很有趣。所以我看了看。对于您的问题,我有一个可行的解决方案,但感觉不好。也许有人会找到更清洁的解决方案。

package main

import (
    "fmt"
    "strings"

    "github.com/go-gota/gota/dataframe"
    "github.com/go-gota/gota/series"
)

func main() {
    csvStr := `accountId,deposit,Withdrawals
anil0001,50,10
vikas0002,10,10
ravi0003,20,10
user1111,NaN,20`

    df := dataframe.ReadCSV(strings.NewReader(csvStr))

    // Within a row, elements are indexed by their column index.
    indexDeposit := 1
    indexWithdrawals := 2

    // Rapply reads the data by rows. 
    // You can access each element of the row using 
    // s.Elem(index) or s.Val(index).
    // To browse by columns use Capply.
    s := df.Rapply(func(s series.Series) series.Series {
        deposit, err := s.Elem(indexDeposit).Int()
        if err != nil {
            return series.Ints("NAN")
        }
        withdrawal, err := s.Elem(indexWithdrawals).Int()
        if err != nil {
            return series.Ints("NAN")
        }
        return series.Ints(deposit - withdrawal)
    })

    // The new series is appended to 
    // the data source via a call to Mutate. 
    // You can print s to read its content.
    df = df.Mutate(s.Col("X0")).
        Rename("deposit_Withdrawals_diff", "X0")

    fmt.Println(df)
}

输出:

$ go run .
[4x4] DataFrame

    accountId deposit Withdrawals deposit_Withdrawals_diff
 0: anil0001  50      10          40
 1: vikas0002 10      10          0
 2: ravi0003  20      10          10
 3: user1111  NaN     20          NaN
    <string>  <int>   <int>       <int>

https://play.golang.org/p/FPIxep_CW9P

于 2021-09-17T13:38:55.473 回答