如何使用NULL填充可变长度的向量以达到固定长度?

huangapple go评论69阅读模式
英文:

How to pad variable-length vectors with NULLs to a fixed length?

问题

我有一组可变长度的整数向量,我想通过在末尾插入NULL值来使它们具有相同的固定长度。我如何实现这个目标?例如,我有一个包含可变长度向量的元组 "a",包括 [1..3][1..5][1..6]。我如何将它们转换为长度为6的向量?

col1    col2    col3
1       1       1
2       2       2
3       3       3
null    4       4
null    5       5
null    null    6
英文:

I have a set of variable-length integer vectors and I want to align them by inserting NULL values at the end to make them have the same fiexed length. How can I achieve this? For example, I have a tuple “a“ containing variable-length vectors [1..3], [1..5], and [1..6]. How can I transform them into vectors of length 6?

col1	col2	col3
1	     1	      1
2	     2        2
3	     3	      3
null	 4	      4
null	 5	      5
null	 null     6

答案1

得分: 1

方法1: 使用 append!

a = [1..3, 1..5, 1..6]

def f(mutable x, N):
    x.copy().append!(array(DOUBLE, N - size(x), N - size(x), NULL))

each(f{, 6}, a)

输出:

col1    col2    col3
  1       1       1
  2       2       2
  3       3       3
          4       4
          5       5
                  6

方法2: 向每个向量添加 6 个 NULL 值,以确保它们的长度大于或等于 6。然后提取每个向量的前六个元素:

a = [1..3, 1..5, 1..6]

def fillNull(x, n):
    take(x < -take(00i, n), n)

each(fillNull{, 6}, a)
英文:

Method 1: Use append!:

a=[1..3,1..5,1..6]
def f(mutable x, N): x.copy().append!(array(DOUBLE,N - size(x),N - size(x),NULL))
each(f{,6},a)

Output:

col1	col2	col3
 1	     1	     1
 2	     2	     2
 3	     3	     3
		 4	     4
	     5	     5
	             6

Method 2: Add 6 NULL values to each of these vectors to ensure their length is greater than or equal to 6. Then extract the first six elements of each vector:

a = [1..3, 1..5, 1..6]
def fillNull(x,n): take(x&lt;-take(00i, n), n)
each(fillNull{, 6}, a)

huangapple
  • 本文由 发表于 2023年7月11日 15:01:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76659408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定