Add a index column to dataframe in gota

Viewed 94

with the following sample, I can add a new column that is diverted from the row values. it's working well.

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)
}

but the question is that, I want to add an index ( row counter) to each row. ( later on I want to join it with a subset of that) So I need an index.

something like

index,accountId,deposit,Withdrawals
1,anil0001,50,10
2,vikas0002,10,10
3,ravi0003,20,10
4,user1111,NaN,20

I see there are no GetIndex or Index methods on series. How can I add this index?

1 Answers

I did it with a global variable ( but I'm not sure it's the best solution for gota, maybe for pure go developer is a good solution :) )

index := 0
s := df.Rapply(func(s series.Series) series.Series {
    index++
    return series.Ints(index)

})
df = df.Mutate(s.Col("X0")).
    Rename("index", "X0")

fmt.Println(df)
Related