Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r's rep() feature in python

Tags:

I am relatively new to python and still figuring out stuff. I wanted to check if there is an equivalent of r's rep command in python to replicate entire vector and not each element. I used numpy.repeat but it only repeats each element given times, is there a way to tweak it to repeat the entire vector?

example:

y=np.repeat(np.arange(0,2),3)
print(y)
array([0, 0, 0, 1, 1, 1])

expected output using r's rep

 a<-c(0,1)
 rep(a,3)
 0 1 0 1 0 1
like image 566
ghub24 Avatar asked Oct 02 '18 13:10

ghub24


2 Answers

I'm no expert in R by any means but as far as I can tell, this is what you are looking for:

>>> np.tile([0, 1], 3)
array([0, 1, 0, 1, 0, 1])
like image 173
Alexander Ejbekov Avatar answered Oct 27 '22 01:10

Alexander Ejbekov


your expected output is not in python (even though that's what you want) but if i try to translate it basically you want something that transforms lets say [0,1,2] to [0,1,2,0,1,2,0,1,2 ...] with any number of repetitions

in python you can simply multiply a list with a number to get that:

lst = [0,1]
lst2  = lst*3
print(lst2)

this will print [0, 1, 0, 1, 0, 1]

like image 30
AntiMatterDynamite Avatar answered Oct 27 '22 00:10

AntiMatterDynamite