1

i am looking for a way to duplicate value inside a numpy array in python according how many element it has inside (Len(-)). It looks like this:

a = [ [1]
      [2]
      [3]
    ]

after duplicating the values inside:

a = [ [1]
      [2]
      [3]
      [1]
      [2]
      [3]
      [1]
      [2]
      [3]
    ]

it is only an simple example. I need this to be done on a big data set.

2
  • Despite accepting an answer it appears that your question is incomplete. Commented Sep 13, 2020 at 20:27
  • If you choose to use np.tile, pay attention to the number of dimensions of your array, and the functions docs. Commented Sep 14, 2020 at 5:41

2 Answers 2

2

You can try with list comprehension. Like this,

import numpy as np

a =np.array( [ [1],  [2], [3],])

arr = [[list(a[i]) for i in range(len(a))] for i in range(len(a))]
print(arr)   

If you want to in 2-d array you can also try in this way,

a =np.array( [ [1],[2], [3],])

arr = [[list(a[i]) for i in range(len(a))] for i in range(len(a))]
arr = sum(arr, [])
print(arr)       # [[1], [2], [3], [1], [2], [3], [1], [2], [3]]
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer. I did use your code and then convert the list to an numpy array as follow: new_testing_images = np.asarray(tmp_testing_images, dtype=np.float32) now I expected to have a shape of (9, 28,28,1) but I got (3,3,28,28,1) why is that?
If you got a 5d array like that, then you clearly didn't start with a (n,1) array (as per your example). It's hard to guess what your really started with, or what kind of expansion you required. If this really is a numpy array, why did you accept a list comprehension solution?
second solution works fine actually. At the end I should convert the list to a numpy array.
0
In [1]: a = np.arange(1,4).reshape(3,1)
In [2]: a
Out[2]: 
array([[1],
       [2],
       [3]])
In [3]: np.tile(a,(3,1))
Out[3]: 
array([[1],
       [2],
       [3],
       [1],
       [2],
       [3],
       [1],
       [2],
       [3]])

The tile arguments will need to be adjusted if your array has more than 2 dimensions. Read its docs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.