基于Python

时间:2017-04-19 19:53:57

标签: python arrays numpy indexing

我有一些实验数据,数据以周期性时间间隔记录。如果测量属性的值为0,则不记录相应的时间戳和属性(0)的值。但是,出于分析目的,我需要在其值为0的相应时间向测量属性数组添加0。

以下简单示例显示了我的问题

loggedTimes = numpy.array([0,    10,   20,  40,  50, 80, 90, 100])
property    = numpy.array([1500, 2000, 500, 75,  60, 45, 37, 0])

所有可能的记录时间均为:

allTimes = numpy.array([0,10,20,30,40,50,60,70,80,90,100]

因此,在30,60和70时,属性的值为0.因此,我需要在属性数组中的相应位置添加一个0,结果是:

allTimes          = numpy.array([0,    10,   20,  30, 40, 50, 60, 70, 80, 90, 100]
propertyCorrected = numpy.array([1500, 2000, 500, 0,  75, 60, 0,  0,  45, 37, 0])

有没有一种聪明的方法可以在不使用循环的情况下完成此操作这是因为我的实验数据非常大,而且我有多次实验运行,所以循环太慢,特别是如果我需要从文本文件重新加载实验数据。

如果有帮助,所有时间和属性值都是整数。

谢谢!

2 个答案:

答案 0 :(得分:4)

如果 allTimes loggedTimes 数组都已排序,那么您可以开始这样做:

 # By using a double-quoted string, the shell expands $v up front.
 v=17
 powershell -noprofile "(get-date).Year -like '*$v'"

 # It gets trickier if you want to reference PS variables too.
 # Note how the PS variable's $ is \-escaped so that the shell doesn't interpret it.
 v=$HOME
 powershell -noprofile "\$HOME -eq '$v'"

 # More robust variant that passes the value as an argument to a script block.
 v=17
 powershell -noprofile '. { param($v) (get-date).Year -like "*$v" }' "$v"

答案 1 :(得分:2)

您也可以使用np.in1d来完成同样的工作。

np.searchsorted

虽然经过粗略的性能测试,{{1}}的性能会有明显改善。