英文:
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<-take(00i, n), n)
each(fillNull{, 6}, a)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论