Python中值之间的零填充

时间:2013-04-24 09:51:24

标签: python python-2.7 numpy

我在低通插值时遇到问题,在处理之前我必须用零填充1D数组。

我有这样的事情:[1 2 3 4 5 6]

我希望有这样的数组[1 0 2 0 3 0 4 0 5 0 6]所以它在数组中是L-1个零,其中L是在零填充之前数组内的所有值的数量。

如何在Python中完成?

6 个答案:

答案 0 :(得分:12)

您可以将未填充的值列表分配到另一个零列表的切片中:

original_list = range(1,7)                 # [1,2,3,4,5,6]
padded_list = [0]*(2*len(original_list)-1) # [0,0,0,0,0,0,0,0,0,0,0]
padded_list[::2] = original_list           # [1,0,2,0,3,0,4,0,5,0,6]

这也可以转换为numpy,但正如Jaime在评论中指出的那样,它更容易使用numpy.insert

import numpy as np

arr = np.arange(1, 7)              # array([1, 2, 3, 4, 5, 6])
np.insert(arr, slice(1, None), 0)  # array([1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6])

答案 1 :(得分:1)

我必须实时应用更大量的数据,所以我检查了性能,np.insert似乎是Python 2.7中最慢的一个:

np.insert:                     1.393 ms
list:                          0.406 ms
np.repeat then zero out:       0.409 ms
np.zeros then assign value:    0.073 ms

这是测试代码:

import time
import numpy as np

start = 0
limit = 30000000

def tic():
    global start
    start = time.clock()

def toc(text):
    print("%-30s %.3f ms" % (text, time.clock()-start))

original_list = range(1,limit)
original_array = np.arange(1, limit)

tic()
insert_array = np.insert(original_array, slice(1, None), 0)
toc("np.insert:")

tic()
padded_list = [0]*(2*len(original_list)-1)
padded_list[::2] = original_list
toc("list:")

tic()
repeat_array = np.repeat(original_array, 2)
repeat_array[1::2] = 0
toc("np.repeat then zero out:")

tic()
padded_array = np.zeros(2*len(original_list)-1, dtype=original_array.dtype)
padded_array[::2] = original_array
toc("np.zeros then assign value:")

答案 2 :(得分:0)

l = [1, 2, 3, 4, 5, 6]

def zero_pad(l):
    r = []
    for x in l:
        r.append(x)
        r.append(0)
    return r[:-1]

print zero_pad(l)

将打印:

[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]

答案 3 :(得分:0)

一种简单的方法:

>>> i = [1,2,3,4,5,6]
>>> [i.insert(i.index(x)+1,0) for x in i[:-1]]
[None, None, None, None, None]
>>> i
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]

与上述相同,扩展:

>>> for x in i[:-1]:
...     i.insert(i.index(x)+1,0)
...
>>> i
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]

答案 4 :(得分:0)

def zero(array):
    for i in range(1, len(array)):
        array.insert(i+i-1,0)
    return array

array = [1, 2, 3, 4, 5, 6]
newArray = zero(array)

答案 5 :(得分:0)

强制itertools方法:

>>> from itertools import izip, repeat, chain
>>> list(chain.from_iterable(izip(el, repeat(0))))[:-1]
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]

更好itertools方法......

from itertools import islice, izip, repeat, chain
blah = list (islice (chain.from_iterable (izip(repeat (0), your_seq)), 1, None))