python - 在 Python 中用零填充多个值

标签 python numpy

在另一个 SO 中,这是在 numpy.array 中的值之间添加单个零的解决方案:

import numpy as np

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

如何在原始数组中的每个值之间添加更多零?例如,5 个零:

np.array([1, 0, 0, 0, 0, 0,
          2, 0, 0, 0, 0, 0,
          3, 0, 0, 0, 0, 0,
          4, 0, 0, 0, 0, 0,
          5, 0, 0, 0, 0, 0, 6])

最佳答案

您可以创建一个 2dim 数组,并将其展平:

import numpy as np
a = np.arange(1,7)
num_zeros = 5
z = np.zeros((a.size, num_zeros))

np.append(a[:,np.newaxis], z, axis=1)
array([[ 1.,  0.,  0.,  0.,  0.,  0.],
       [ 2.,  0.,  0.,  0.,  0.,  0.],
       [ 3.,  0.,  0.,  0.,  0.,  0.],
       [ 4.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  0.,  0.,  0.,  0.,  0.],
       [ 6.,  0.,  0.,  0.,  0.,  0.]])

np.append(a[:,np.newaxis], z, axis=1).flatten()
array([ 1.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  3.,
        0.,  0.,  0.,  0.,  0.,  4.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,
        0.,  0.,  0.,  0.,  6.,  0.,  0.,  0.,  0.,  0.])

np.append(a[:,np.newaxis], z, axis=1).flatten()[:-num_zeros]
array([ 1.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  3.,
        0.,  0.,  0.,  0.,  0.,  4.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,
        0.,  0.,  0.,  0.,  6.])

关于python - 在 Python 中用零填充多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16373758/

相关文章:

python - Scrapy(Python): Iterating over 'next' page without multiple functions

python - 如何增加TreeView中显示的数据行数?

Python-删除与多个 ‘or’匹配的文件

python - 如何从 python 中的另一个 .py 文件访问全局变量?

python - np.unravel_index 的直观解释是什么?

python - 使用 numpy 数组计算时放置条件

python - 从随机森林中获取树木

python - 测试 Numpy 数组是否包含给定行

python - 线性方程的 Numpy 语法

numpy - 理解 NumPy 的非零函数