简体   繁体   中英

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. 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.

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.

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. 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.

You can use 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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