【发布时间】:2019-03-21 11:14:46
【问题描述】:
我有 Python 和 R 背景,并且习惯于使用数据框。 如果我有下表:
>>> table
ID Phone Email Value
------------------------------
ID1 15555555555 None None
ID2 None 3Email None
ID3 3123 4Email aaa
从table 派生两个表如下所示:
>>> table1=table[["ID","Phone","Email"]]
>>> table1
ID Phone Email
------------------------
ID1 15555555555 None
ID2 None 3Email
ID3 3123 4Email
>>> table2=table[["ID","Value"]]
>>> table2
ID Value
---------
ID1 None
ID2 None
ID3 aaa
现在我正在尝试使用 Golang 实现相同的目标。下面是我的第一步:
package main
import (
"fmt"
)
type Identification struct {
ID string
Phone int64
Email string
Value string
}
func main() {
// define slice of Identification
var idents []Identification
idents = append(idents, Identification{ID: "ID1", Phone: 15555555555})
idents = append(idents, Identification{ID: "ID2", Email: "3Email"})
idents = append(idents, Identification{ID: "ID3", Phone:3123, Email: "4Email", Value: "aaa"})
fmt.Println(idents)
}
结果:
[{ID1 15555555555 } {ID2 0 3Email } {ID3 3123 3Email aaa}]
我的问题是如何像示例中的 Python 一样对 idents 进行切片?
【问题讨论】:
-
struct具有固定的“形状”,因此您不能直接执行此操作。你为什么想要呢?您可以将字段保留在那里,并在处理时忽略它们。 -
这似乎是一个 XY 问题。你的最终目标是什么?
-
@Flimzy 我的目标是从源中导入行数据,然后根据特定键对其进行切片并将其插入数据库中的不同表中
-
那么没有必要在结构中“切片”它。只需将您关心的列插入相应的表中即可。
标签: dataframe go data-structures struct