user14339031
user14339031

Reputation:

repeating a numpy array N times

hii experts i have a 1d numpy array and i want to repeat it 3 times vertically,

my_input_array = [-1.02295637 -0.60583836 -0.42240581 -0.78376377 -0.85821456]

i tried the below code

import numpy as np
x=np.loadtxt(my_input_array)
x.concatenate()

however i get error...in this way...hope i will get some solution.Thanks.

my expected output should be as below

 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 

Upvotes: 1

Views: 5380

Answers (3)

Jarad
Jarad

Reputation: 18893

numpy.tile

np.tile(my_input_array, 3)

Output

array([-1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456,
       -1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456,
       -1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456])

Edit: just noticed @hpaulj's answer. I'll still leave my answer but he mentioned np.tile first.

Upvotes: 2

Raghav Gupta
Raghav Gupta

Reputation: 464

Just use tile method which multiplies the array with given shape and reshape method to structure it. Use x.shape[0]*x.shape[1] to change it into a column vector without explicitly giving the shape dimensions!

x=np.tile(x,(3,1))
y=x.reshape(x.shape[0]*x.shape[1])

Upvotes: 1

IoaTzimas
IoaTzimas

Reputation: 10624

This is what you want:

x=np.concatenate([my_input_array, my_input_array, my_input_array])
for i in x:
    print(i)

Output:

-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456

Upvotes: 0

Related Questions