简体   繁体   English

使用来自另一个数组的值在python中创建带有值的二维数组

[英]Creating 2D array with values in python with values from another array

i am trying to get better at coding in python and am stuck at a fairly standard problem.我正试图在 python 中更好地编码,但被困在一个相当标准的问题上。 I have a given array, and need to create an array with double the lines.我有一个给定的数组,需要创建一个双倍行的数组。 The new array should correspond to the original in such a way, that two lines in the new array contain the same values as one value in the original.新数组应该以这样一种方式对应于原始数组,即新数组中的两行包含与原始数组中的一个值相同的值。 I am working with Python 3.7 and numpy arrays.我正在使用 Python 3.7 和 numpy 数组。

Example:例子:

original_array = [[1,2,3],
                  [4,5,6],
                  [7,8,9]]
result = [[1,2,3],
          [1,2,3],
          [4,5,6],
          [4,5,6],
          [7,8,9],
          [7,8,9]]

There is a manual way to do that:有一种手动方法可以做到这一点:

result = np.zeros((original_array.shape[0]*2, original_array.shape[1]))
for i in range(result.shape[0]):
    result[i]=original_array[i//2]

However since my application deals with very large arrays, i am trying to use library-functions as much as possible.但是,由于我的应用程序处理非常大的数组,因此我尝试尽可能多地使用库函数。 After searching for a bit, i came up with the following:经过一番搜索,我想出了以下内容:

result = np.fromfunction(lambda i,j: original_array[i//2][j], 
                         (original_array.shape[0]*2, original_array.shape[1]),
                         dtype=int)

However, this call produces a 4D array where most of the values are only from the first line, so it obviously does not work in the intended way.但是,此调用会生成一个 4D 数组,其中大部分值仅来自第一行,因此它显然无法按预期方式工作。

Why does this call fail and how can i achieve the wanted effect?为什么这个调用会失败,我怎样才能达到想要的效果?

Edit:编辑:

I found out why the call failed.我发现了呼叫失败的原因。 np.fromfunction(...) does not iterate directly over the indices, it gives them as arrays. np.fromfunction(...) 不直接迭代索引,而是将它们作为数组提供。 When the resulting array differs from the original in size, then the access of the original array over indices does not work anymore in the intended way.当生成的数组与原始数组的大小不同时,原始数组对索引的访问不再以预期的方式工作。

Using np.repeat(...) as StupidWolf suggested works.使用 np.repeat(...) 作为 StupidWolf 建议的作品。

You can use np.repeat:您可以使用 np.repeat:

np.repeat(original_array,2,axis=0)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM