How to convert 2D slice rows from excel to DataFrame in Golang

176 views Asked by At

I have to read data from excel and convert it into DataFrame. but rows are of type 2D slice. How can I convert it to corresponding DataFrame?

import (
    "fmt"

    "github.com/go-gota/gota/dataframe"
    
    "github.com/xuri/excelize/v2"
)

func main() {
f, err := excelize.OpenFile(sheetPath)
if err != nil {
       fmt.Print(err)
    }

rows, err := f.GetRows(sheetName)
if err != nil {
    fmt.Print(err)
     }
df := dataframe.LoadRecords(rows, dataframe.HasHeader(true))

}

I'm getting following error:

panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:

EDIT:

I have 4 columns. I've noticed that the 25th row contains a value only in the first column. When I attempt to create a DataFrame by including up to the 25th row, it works fine. However, when I include the 25th row and try to create a DataFrame, I encounter an 'index out of range' error. I need up to 30 rows to dataframe. Therefore, should I address the issue of empty values before converting the data into a DataFrame?

1

There are 1 answers

0
whitespace On
package main

import (
    "fmt"

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

    "github.com/xuri/excelize/v2"
)

func main() {
    
    f, err := excelize.OpenFile(sheetPath)
    if err != nil {
        fmt.Print(err)
    }

    rows, err := f.GetRows(sheetName)
    if err != nil {
        fmt.Print(err)
    }
    for row_index, row := range rows {
        if len(row) < 8 { #replace this with number of columns
            corrected_row := [8]string{}
            for cell_index, cell_value := range row {
                corrected_row[cell_index] = cell_value
            }
            fmt.Println(corrected_row)
            rows[row_index] = corrected_row[:]
        }
    }
    df := dataframe.LoadRecords(rows, dataframe.HasHeader(true))
    fmt.Println(df)

}

you can replace the row, which has less cells before converting to a dataframe.