通过使用先前的值填充中间的值来增加数组的大小

亚哈希

我有一个大小为19的数组。我想将其大小增加到30(new_array)。

size =len(VM)    
index = np.linspace(1,size,size)/size
index30 = np.linspace(1,30,30)/30
new_array = np.empty(shape=30)

VM是大小为19的数组

指数

[0.05263158 0.10526316 0.15789474 0.21052632 0.26315789 0.31578947
 0.36842105 0.42105263 0.47368421 0.52631579 0.57894737 0.63157895
 0.68421053 0.73684211 0.78947368 0.84210526 0.89473684 0.94736842
 1.        ]

指数30

[0.03333333 0.06666667 0.1        0.13333333 0.16666667 0.2
 0.23333333 0.26666667 0.3        0.33333333 0.36666667 0.4
 0.43333333 0.46666667 0.5        0.53333333 0.56666667 0.6
 0.63333333 0.66666667 0.7        0.73333333 0.76666667 0.8
 0.83333333 0.86666667 0.9        0.93333333 0.96666667 1.        ]

要填充new_array:

如果我们考虑index array的前两个元素0.05263158 0.10526316,则index30 array的所有值在这两个值之间,则它们在new_array中的对应位置应使用与0.05263158index数组中的值位置相对应的VM array的值来填充,依此类推。我可以使用for循环来执行此操作,但我正在寻找更有效的方法来执行此操作?

输入:

[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

预期输出:

[nan,1,1,2,3,3,4,5,5,6,6,7,8,8,9,10,10,11,12,12,13,13,14,15,15,16,17,17,18,19]
我想要一片T骨牛排

编辑:您可以使用np.piecewisenp.less_equalnp.outer以创建condlistnp.append一个nanVM创建的值funclist,例如:

new_array = np.piecewise( x = index30, 
                          condlist = np.less_equal.outer(indexVM, index30), 
                          funclist = np.append(VM,np.nan))

如果您愿意使用pandas,可以使用reindex方法'ffill'

import numpy as np
import pandas as pd

VM = np.arange(1,20)
size = len(VM)    
indexVM = np.linspace(1,size,size)/size
index30 = np.linspace(1,30,30)/30 

new_array = pd.Series(VM, index=indexVM).reindex(index30, method='ffill').values
print (new_array)
array([nan,  1.,  1.,  2.,  3.,  3.,  4.,  5.,  5.,  6.,  6.,  7.,  8.,
        8.,  9., 10., 10., 11., 12., 12., 13., 13., 14., 15., 15., 16.,
       17., 17., 18., 19.])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章