重复一个numpy数组的每个元素5次

编程入门 行业动态 更新时间:2024-10-21 06:30:08
本文介绍了重复一个numpy数组的每个元素5次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 import numpy as np data = np.arange(-50,50,10) print data [-50 -40 -30 -20 -10 0 10 20 30 40]

我要重复数据的每个元素5次,并按如下所示制作新数组:

I want to repeat each element of data 5 times and make new array as follows:

ans = [-50 -50 -50 -50 -50 -40 -40 ... 40]

我该怎么办?

将整个数组重复5次怎么样?

What about repeating the whole array 5 times?

ans = [-50 -40 -30 -20 -10 0 10 20 30 40 -50 -40 -30 -20 -10 0 10 20 30 40 -50 -40 -30 -20 -10 0 10 20 30 40 -50 -40 -30 -20 -10 0 10 20 30 40 -50 -40 -30 -20 -10 0 10 20 30 40 .......]

推荐答案

In [1]: data = np.arange(-50,50,10)

要重复每个元素5次,请使用 np.repeat :

To repeat each element 5 times use np.repeat:

In [3]: np.repeat(data, 5) Out[3]: array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30, -30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 30, 30, 30, 30, 30, 40, 40, 40, 40, 40])

要重复数组5次,请使用 np.tile :

To repeat the array 5 times use np.tile:

In [2]: np.tile(data, 5) Out[2]: array([-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40])

但是请注意,有时您可以利用 NumPy广播代替用重复的元素创建一个更大的数组.

Note, however, that sometimes you can take advantage of NumPy broadcasting instead of creating a larger array with repeated elements.

例如,如果

z = np.array([1, 2]) v = np.array([[3], [4], [5]])

然后添加这些数组以生成

then to add these arrays to produce

[[4 5] [5 6] [6 7]]

您不需要使用图块:

In [12]: np.tile(z, (3,1)) Out[12]: array([[1, 2], [1, 2], [1, 2]]) In [13]: np.tile(v, (1,2)) Out[13]: array([[3, 3], [4, 4], [5, 5]]) In [14]: np.tile(z, (3,1)) + np.tile(v, (1,2)) Out[14]: array([[4, 5], [5, 6], [6, 7]])

相反,NumPy将为您广播数组:

Instead, NumPy will broadcast the arrays for you:

In [15]: z + v Out[15]: array([[4, 5], [5, 6], [6, 7]])

更多推荐

重复一个numpy数组的每个元素5次

本文发布于:2023-11-30 20:53:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651440.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!