首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中创建时间序列数据

在python中创建时间序列数据
EN

Stack Overflow用户
提问于 2018-08-06 07:31:32
回答 2查看 973关注 0票数 1

我有两个numpy数组中的数据:

代码语言:javascript
复制
data = [0.1, 0.3, 0.4, 0.6, 0.7]
time = [10,25, 27, 35, 42]

data对应于time等效索引处的值

我想基于一个新的time数组创建另一个数组,如下所示:

代码语言:javascript
复制
newtime = [10, 20, 30, 40, 50]

新的数据数组应该如下所示:

代码语言:javascript
复制
[0.1, 0.1, 0.4,0.6, 0.7]

其对应于每个新时间的data的值。例如,在10s时,该值为0.1,而在20秒时,该值未更改,因此两者都应为0.1

问题是用python从数据数组和时间数组创建“新数据”numpy最简单的方法是什么?除了numpy,我也很乐意尝试其他的python库。

EN

回答 2

Stack Overflow用户

发布于 2018-08-06 07:59:53

使用searchsorted可能是最快的方法之一。

代码语言:javascript
复制
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)

这将打印出来

代码语言:javascript
复制
[ 0.1  0.1  0.4  0.6  0.7]
票数 1
EN

Stack Overflow用户

发布于 2018-08-14 01:50:39

对于这个任务,你可以使用RedBlackPy,它在linux和macosx上的Python3中是受支持的。RedBalckPy.Series类支持方便的时间序列功能,它始终保持键的排序。在这种情况下,您不需要创建新的Series,因为插值是内置在getitem运算符(Serieskey)中的。您可以使用插值访问任何关键点(在您的情况下为floor)。请参见下面的代码示例:

代码语言:javascript
复制
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)

最后一次打印结果如下:

代码语言:javascript
复制
Series object Untitled
10: 0.1
25: 0.3
27: 0.4
35: 0.6
42: 0.7

有关更多代码示例,请参阅TowardsDataScience上的文章。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51699015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档