Python numpy equivalent of R rep and rep_len functions -
i'd find python (numpy possible)-equivalent of r rep , rep_len functions.
question 1: regarding rep_len function, run,
rep_len(paste('q',1:4,sep=""), length.out = 7) then elements of vector ['q1','q2','q3','q4'] recycled fill 7 spaces , you'll output
[1] "q1" "q2" "q3" "q4" "q1" "q2" "q3" how do recycle elements of list or 1-d numpy array fit predetermined length? i've seen numpy's repeat function lets specify number of reps, doesn't repeat values fill predetermined length.
question 2: regarding rep function, run,
rep(2000:2004, each = 3, length.out = 14) then output
[1] 2000 2000 2000 2001 2001 2001 2002 2002 2002 2003 2003 2003 2004 2004 how make (recycling elements of list or numpy array fit predetermined length , list each element consecutively predetermined number of times) happen using python?
i apologize if question has been asked before; i'm totally new stack overflow , pretty new programming in general.
for rep_len, similar numpy method np.tile except doesn't provide length.out parameter; can implement pretty slice:
x = ['q1', 'q2', 'q3', 'q4'] def np_rep_len(x, length_out): return np.tile(x, length_out // len(x) + 1)[:length_out] np_rep_len(x, 7) # array(['q1', 'q2', 'q3', 'q4', 'q1', 'q2', 'q3'], # dtype='<u2') for rep method, numpy equivalent numpy.repeat, need implement length.out slice:
def np_rep(x, repeat, length_out): return np.repeat(x, repeat)[:length_out] np_rep(x, 3, 10) # array(['q1', 'q1', 'q1', 'q2', 'q2', 'q2', 'q3', 'q3', 'q3', 'q4'], # dtype='<u2')
Comments
Post a Comment