Dataframes with Go, using Gota package.

I was looking for an option in Go to visualize data from a CSV file in form of a dataframe like Pandas in Python. I found the Gota package, a library easy to use. I have a folder of CSV files and is really time-consuming to open MS Excel to open every file and see its content.

So, I write a program that shows a dataframe of a CSV file in the terminal using the Gota package.

First, import the package the program is going to use.

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
    "strings"
    "github.com/go-gota/gota"
)

The user has to write in the terminal the name of the file. Inside the function main, we have to use bufio package to read the name of the file from our terminal. The ReadString method appends "\r\n" to our string, we use TrimSuffix to cut it out from the name of the file.

    func main() {

    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Enter the name of a file with .csv extension: ")

    input, err := reader.ReadString('\n')
    if err != nil {
        fmt.Println("An error occured while reading input. Please try again", err)
        return
    }

    CsvName := strings.TrimSuffix(input,"\r\n")
    if strings.HasSuffix(CsvName, ".csv") {
        OpenCsvFile(CsvName)
    }

Finally, we write a function to generate a dataframe from a CSV file.

func OpenCsvFile(name string) {
    CsvFile, err := os.Open(name)
    if err != nil {
      log.Fatal(err)
    }

    df := dataframe.ReadCSV(CsvFile)
    fmt.Println(df)
}

The completed code here:

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
    "strings"
    "github.com/go-gota/gota/dataframe"
)

func main() {

    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Enter the name of a file with .csv extension or '0.csv' to end the program: ")

    input, err := reader.ReadString('\n')
    if err != nil {
        fmt.Println("An error occured while reading input. Please try again", err)
        return
    }

    CsvName := strings.TrimSuffix(input,"\r\n")
    if strings.HasSuffix(CsvName, ".csv") {
        OpenCsvFile(CsvName)
    }


}
func OpenCsvFile(name string) {
    CsvFile, err := os.Open(name)
    if err != nil {
      log.Fatal(err)
    }

    df := dataframe.ReadCSV(CsvFile)
    fmt.Println(df)
}

Gota is a good option to generate a dataframe, it offers functions to read data from JSON, HTML, and CSV files, and functions to manipulate data in a dataframe. Here is the link to its docs.

The complete code in Github.

Follow me on twitter.