我有两个numpy
数组中的数据:
data = [0.1, 0.3, 0.4, 0.6, 0.7]
time = [10,25, 27, 35, 42]
data
对应于time
等效索引处的值
我想基于一个新的time
数组创建另一个数组,如下所示:
newtime = [10, 20, 30, 40, 50]
新的数据数组应该如下所示:
[0.1, 0.1, 0.4,0.6, 0.7]
其对应于每个新时间的data
的值。例如,在10s
时,该值为0.1
,而在20
秒时,该值未更改,因此两者都应为0.1
问题是用python从数据数组和时间数组创建“新数据”numpy最简单的方法是什么?除了numpy,我也很乐意尝试其他的python库。
发布于 2018-08-06 07:59:53
使用searchsorted可能是最快的方法之一。
import numpy as np
data = np.array([0.1, 0.3, 0.4, 0.6, 0.7])
time = np.array([10,25, 27, 35, 42])
newtime =np.array([10, 20, 30, 40, 50])
newdata = data[ np.searchsorted(time, newtime, side="right") - 1 ]
print(newdata)
这将打印出来
[ 0.1 0.1 0.4 0.6 0.7]
发布于 2018-08-14 01:50:39
对于这个任务,你可以使用RedBlackPy,它在linux和macosx上的Python3中是受支持的。RedBalckPy.Series类支持方便的时间序列功能,它始终保持键的排序。在这种情况下,您不需要创建新的Series,因为插值是内置在getitem运算符(Serieskey)中的。您可以使用插值访问任何关键点(在您的情况下为floor)。请参见下面的代码示例:
import redblackpy as rb
# yours data and time
data = [0.1, 0.3, 0.4, 0.6, 0.7]
time = [10,25, 27, 35, 42]
# create Series object with floor interpolation type
series = rb.Series( index=time, values=data, dtype='float64',
interpolate='floor' )
# now you can access at any key using interpolation,
# it does not create new element, it just use neighbours (t_1 < key < t_2)
# in our case we set floor interpolation, so we get value for t_1
print(series[10]) # prints 0.1
print(series[20]) # prints 0.1
print(series[30]) # prints 0.4
print(series[40]) # prints 0.6
print(series[50]) # prints 0.7
# print Series, Series does not insert this keys
print(Series)
最后一次打印结果如下:
Series object Untitled
10: 0.1
25: 0.3
27: 0.4
35: 0.6
42: 0.7
有关更多代码示例,请参阅TowardsDataScience上的文章。
https://stackoverflow.com/questions/51699015
复制相似问题