python - numpy:通过沿新轴滚动并使用第二个数组中给出的变量移位来广播数组

标签 python arrays numpy

我知道numpy.roll可以沿一个或多个现有轴移动数组。如何在数组 x 上创建一个新轴,沿着该轴我希望数组 shift 滚动其自身的 View 或副本?

示例:

x = np.arange(10)
shift = np.array([2, 4])

#input
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

#output
array(
  [[8, 6],
   [9, 7],
   [0, 8],
   [1, 9],
   [2, 0],
   [3, 1],
   [4, 2],
   [5, 3],
   [6, 4],
   [7, 5]])

编辑:我正在寻找一个通用的解决方案(最好没有循环),它也可以应用于更高维的数组。另一个例子:

x = np.arange(20).reshape(2, 10)
shift = np.array([2, 4])

#input
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

#output
array(
  [[[ 8,  6],
    [ 9,  7],
    [ 0,  8],
    [ 1,  9],
    [ 2,  0],
    [ 3,  1],
    [ 4,  2],
    [ 5,  3],
    [ 6,  4],
    [ 7,  5]],

   [[18, 16],
    [19, 17],
    [10, 18],
    [11, 19],
    [12, 10],
    [13, 11],
    [14, 12],
    [15, 13],
    [16, 14],
    [17, 15]]])

最佳答案

这是一个利用广播的矢量化解决方案,涵盖通用n-dim数组情况 -

np.take(x,(-shift + np.arange(x.shape[-1])[:,None]),axis=-1)

示例运行

1) x1D -

In [114]: x = np.arange(10)
     ...: shift = np.array([2, 4])

In [115]: np.take(x,(-shift + np.arange(x.shape[-1])[:,None]),axis=-1)
Out[115]: 
array([[8, 6],
       [9, 7],
       [0, 8],
       [1, 9],
       [2, 0],
       [3, 1],
       [4, 2],
       [5, 3],
       [6, 4],
       [7, 5]])

2) x2D -

In [116]: x = np.arange(20).reshape(2, 10)
     ...: shift = np.array([2, 4])

In [117]: np.take(x,(-shift + np.arange(x.shape[-1])[:,None]),axis=-1)
Out[117]: 
array([[[ 8,  6],
        [ 9,  7],
        [ 0,  8],
        [ 1,  9],
        [ 2,  0],
        [ 3,  1],
        [ 4,  2],
        [ 5,  3],
        [ 6,  4],
        [ 7,  5]],

       [[18, 16],
        [19, 17],
        [10, 18],
        [11, 19],
        [12, 10],
        [13, 11],
        [14, 12],
        [15, 13],
        [16, 14],
        [17, 15]]])

关于python - numpy:通过沿新轴滚动并使用第二个数组中给出的变量移位来广播数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176222/

相关文章:

python - Pandas :对一系列 bool 值进行和/或操作

python - Python 3.5.3 中相同的字符串怎么可能是不同的对象?

arrays - 在数据存储中的 JSON 类型字段中插入空数组

python - 在 DataFrame 中,我们如何获取特定列中包含 0 的索引列表?

python - 大于或等于python中的分箱

python - 更快的图像标准化(numpy 数组)

python - PySpark - 从集合传递到 RDD

c++ - 在 C++ 中将某种结构化的文本文件读入数组

javascript - Angular 替换 $scope 和 $apply 中的数组不起作用

arrays - Swift - 如果字符串为零。不要将它添加到数组中