【问题标题】:Creating a numpy array with repetitive pattern创建具有重复模式的 numpy 数组
【发布时间】:2015-11-25 19:11:51
【问题描述】:

我正在尝试创建一个大小为 6*n 的数组,这样对于数组中的每批 6 个单元格,我将拥有以下整数值:

a = [n-2, n-1,n,n,n+1,n+1,n+2,n+3]

我能想到的平庸方式是使用这个例程:

a = []
for i in xrange(n):
    np.append(a,[n-2, n-1,n,n,n+1,n+1,n+2,n+3])

但是有没有更聪明更快的方法呢?

【问题讨论】:

  • 您的示例仍然存在问题,这使得您更难以准确理解您想要什么。如果你想要一个列表,你可以使用a.extend([n-2, n-1,n,n,n+1,n+1,n+2,n+3]),或者如果你想要嵌套列表,你可以使用a.append([n-2, n-1,n,n,n+1,n+1,n+2,n+3])
  • 你确定6?你的模式的长度是8。您的代码给出了一个长度为8*n 的数组。你的意思是在你的循环中有i吗?

标签: python arrays python-2.7 numpy


【解决方案1】:

你可以使用numpy.tile:

>>> n = 6
>>> arr = np.array([n-2, n-1, n, n, n+1, n+1, n+2, n+3])
>>> np.tile(arr, n)
array([4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8,
       9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7,
       8, 9])
# Reshape to get the desired output
>>> np.tile(arr, n).reshape(n, arr.size)
array([[4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9],
       [4, 5, 6, 6, 7, 7, 8, 9]])

【讨论】:

  • 我认为不需要reshape。 OP 的示例给出了一个 1d (8*n,) 形状的数组。
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
相关资源
最近更新 更多