go - 如何基于Go中的日期列对CSV数据进行排序

标签 go

我是GO的新手。请问有人可以帮助您根据日期列对CSV([] []字符串)数据进行排序吗?
因为数据中存在重复项,所以我将其转换为map以删除重复项并返回到slice。但是到了这一步,数据尚未排序。

如何根据日期列对数据排序?
有人可以帮忙吗?

删除重复项

func removeDuplicatesFromListQuote(quotes [][]string) [][]string {
dict := make(map[string][]string)
for i, val := range quotes {
    if i == 0 {
        continue
    }
    dict[val[0]] = []string{val[1], val[2], val[3], val[4], val[5]}
}

var unique [][]string
newLine := make([]string, 0)
unique = append(unique, []string{"Date", "Open", "High", "Low", "Close", "Volume"})
for key, val := range dict {
    newLine = []string{key, val[0], val[1], val[2], val[3], val[4]}
    unique = append(unique, newLine)
}

Ë

数据排序
Date,Open,High,Low,Close,Volume 05111985,0.33,0.34,0.33,0.33,26885600 12021986,0.43,0.43,0.42,0.43,33264000 11051999,1.60,1.65,1.56,1.60,114648800 03052000,4.25,4.33,3.99,4.11,122449600 01112004,3.75,3.80,3.72,3.75,150512600 19072017,150.48,151.42,149.95,151.02,20923000 17091992,1.69,1.69,1.62,1.64,43108800 28051985,0.32,0.32,0.30,0.30,127741600 24071985,0.29,0.30,0.29,0.29,42179200 06042000,4.67,4.80,4.40,4.47,64906800 13042009,17.14,17.28,17.00,17.17,97309100 26022018,176.35,179.39,176.21,178.97,38162200 15051995,1.54,1.56,1.52,1.56,98338800 23031999,1.23,1.23,1.17,1.18,103888400 11092003,1.59,1.63,1.58,1.61,53421200 14072017,147.97,149.33,147.33,149.04,20132100 07031990,1.25,1.29,1.25,1.26,51055200 06061995,1.56,1.58,1.55,1.57,78817200

最佳答案

您可以添加一些sort方法。排序以调用和排序数据。数据的第一列显示为日期格式为MMDDYYYY。

package main

import (
    "fmt"
    "sort"
    "time"
)

type CSV [][]string

// Determine if one CSV line at index i comes before the line at index j.
func (data CSV) Less(i, j int) bool {
    dateColumnIndex := 0
    date1 := data[i][dateColumnIndex]
    date2 := data[j][dateColumnIndex]
    timeT1, _ := time.Parse("01022006", date1)
    timeT2, _ := time.Parse("01022006", date2)

    return timeT1.Before(timeT2)
}

// Other functions required for sort.Sort.
func (data CSV) Len() int {
    return len(data)
}
func (data CSV) Swap(i, j int) {
    data[i], data[j] = data[j], data[i]
}

func main() {
    data := [][]string{
        []string{"05111985", "0.33", "0.34", "0.33"},
        []string{"11051999", "1.60", "1.65", "1.56"},
        []string{"12021986", "0.43", "0.43", "0.42"},
    }

    // Sort the data in place using the methods above.
    sort.Sort(CSV(data))
    fmt.Println(data)
}

输出:[[05111985 0.33 0.34 0.33] [12021986 0.43 0.43 0.42] [11051999 1.60 1.65 1.56]]

关于go - 如何基于Go中的日期列对CSV数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61802731/

相关文章:

go - 使用 cookie 测试请求

go - 如何在 golang 中检查特定目录是否有 mount --bind ?

go - Helm go sdk 从外部位置安装图表

go - 如何使用带有用户 token E2E 的 CF 客户端

macos - 如何从 go 启动 vim?

json - 如何解决本程序打印出的JSON数据?

go - 如何在数组列表中保存[] byte数据

json - Go:JSON值未解析?

go - 'go.tools' 的权限被拒绝错误

go - 使用 redigo 池时并发后 TIME_WAIT 太多