Skip to content

Instantly share code, notes, and snippets.

@hsleonis
Created October 24, 2016 19:46
Show Gist options
  • Save hsleonis/010117e88b95fb1c9eaf4a0aef3de01c to your computer and use it in GitHub Desktop.
Save hsleonis/010117e88b95fb1c9eaf4a0aef3de01c to your computer and use it in GitHub Desktop.
Read file and use CSV data in GoLang
package main
import (
"os"
"encoding/csv"
"fmt"
"strconv"
"sort"
"time"
)
func main(){
f, err := os.Open("./Environmental_Data_Deep_Moor_2015.txt")
if err!=nil{
panic(err)
}
defer f.Close()
rdr := csv.NewReader(f)
rdr.Comma = '\t'
rdr.TrimLeadingSpace = true
rows, err := rdr.ReadAll()
if err!=nil{
panic(err)
}
start:=time.Now()
fmt.Println("Total record:", len(rows)-1)
if len(rows)-1>0{
fmt.Println("Mean Air Temparature:", mean(rows, 1))
fmt.Println("Mean Barometric pressure:", mean(rows, 2))
fmt.Println("Mean Wind Speed", mean(rows, 7))
fmt.Println("Median Air Temparature:", median(rows, 1))
fmt.Println("Median Barometric pressure:", median(rows, 2))
fmt.Println("Median Wind Speed", median(rows, 7))
}
end:=time.Now()
fmt.Println(end.Sub(start))
}
func mean(rows [][]string, idx int) float64{
var total float64
for i,row := range rows{
if i!=0{
val, _ := strconv.ParseFloat(row[idx],64)
total+=val
}
}
return total/ float64(len(rows)-1)
}
func median(rows [][]string, idx int) float64{
var sorted[] float64
for i,row := range rows{
if i!=0{
val, _ := strconv.ParseFloat(row[idx],64)
sorted = append(sorted, val)
}
}
sort.Float64s(sorted)
middle := len(rows)/2
if len(rows)%2==0{
high := sorted[middle]
low := sorted[middle-1]
return (high+low)/2
}
return sorted[middle]/2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment