我想找到R、rep和rep_len函数的python (numpy是可能的)rep。
问题1:关于rep_len函数,假设我运行,
rep_len(paste('q',1:4,sep=""), length.out = 7)然后向量['q1','q2','q3','q4']的元素将被回收,以填充7个空格,您将得到输出
[1] "q1" "q2" "q3" "q4" "q1" "q2" "q3"如何循环列表或一维numpy数组的元素以适应预定的长度?根据我所看到的,numpy的reps函数允许您指定一定数量的代表,但不重复值来填充预定的长度。
问题2:关于rep函数的,假设我运行,
rep(2000:2004, each = 3, length.out = 14)那么输出是
[1] 2000 2000 2000 2001 2001 2001 2002 2002 2002 2003 2003 2003 2004 2004如何使用python实现(循环列表或numpy数组的元素以适应预定长度并连续列出每个元素的预定次数)?
如果之前有人问过这个问题,我很抱歉;我对堆栈溢出完全陌生,对一般的编程也很陌生。
发布于 2017-09-12 03:04:30
NumPy实际上提供了与rep_len相当的功能。是numpy.resize
new_arr = numpy.resize(arr, new_len)请注意,resize方法使用零代替重复元素,因此arr.resize(new_len)不执行您想要的操作。
至于rep,我不知道类似的情况。有numpy.repeat,但它不允许限制输出的长度。(重复的全向量功能也有numpy.tile,但同样没有length.out等效。)您可以对结果进行切片,但是它仍然会花费所有的时间和内存来生成未截断的数组:
new_arr = numpy.repeat(arr, repetitions)[:new_len]发布于 2017-12-20 23:17:55
numpy.repeat()的作用类似于R的代表()函数和each=True。当使用each=False时,可以通过换位来实现回收:
import numpy as np
def np_rep(x, reps=1, each=False, length=0):
""" implementation of functionality of rep() and rep_len() from R
Attributes:
x: numpy array, which will be flattened
reps: int, number of times x should be repeated
each: logical; should each element be repeated reps times before the next
length: int, length desired; if >0, overrides reps argument
"""
if length > 0:
reps = np.int(np.ceil(length / x.size))
x = np.repeat(x, reps)
if(not each):
x = x.reshape(-1, reps).T.ravel()
if length > 0:
x = x[0:length]
return(x)例如,如果我们设置each=True:
np_rep(np.array(['tinny', 'woody', 'words']), reps=3, each=True)...we get:
array(['tinny', 'tinny', 'tinny', 'woody', 'woody', 'woody', 'words', 'words', 'words'],
dtype='<U5')但是当each=False:
np_rep(np.array(['tinny', 'woody', 'words']), reps=3, each=False)...the的结果是:
array(['tinny', 'woody', 'words', 'tinny', 'woody', 'words', 'tinny', 'woody', 'words'],
dtype='<U5')请注意,x会被压平,结果也是平坦的。要实现length参数,需要计算所需的最小reps数,然后将结果截断到所需的长度。
发布于 2017-09-12 02:42:31
对于rep_len,类似的numpy方法是np.tile,只是它不提供length.out参数;但是您可以很容易地用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')对于rep方法,numpy等效为numpy.repeat,还需要用片实现length.out:
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')https://stackoverflow.com/questions/46166933
复制相似问题