python 中两个列表中重叠值的平均值
Average around overlapping values in two lists in python
我有 4 个列表,其中包含 UNIX 中的时间数据和相应的速度。一组比另一组大。我想在较小列表的每个匹配时间戳处找到较大列表的找到值前后几个值的平均速度。
t1 = [2, 5, 7]
t2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
v1 = [0.5, 1, 0.7]
v2 = [0.1, 0.5, 1, 1.3, 1.4, 1.8, 0.9, 2, 1.5, 1.2]
所以如果 t1 和 t2 匹配,我想得到那个时间之前和之后的 x 值的平均速度。
假设 x = 1
在这种情况下,它应该给我 (0.1, 0.5, 1) (1.3, 1.4, 1.8) 和 (1.8, 0.9, 2)
的平均值
尝试
import numpy as np
for num in t1: #for each value in t1
try:
match_index=t2.index(num) #check if match exists
except:
match_index=-1 #otherwise set it to -1
if(match_index!=-1): #if match was found
my_list=[] #make an empty list
if(match_index==0): #if index was 0, then nearby 3 elements can't be found, only 2 can
my_list=v2[:match_index+2]
elif(match_index==len(v2)-1): #similarly if index was for last element
my_list=v2[match_index-1:]
else:
my_list=v2[match_index-1:match_index+2] #normal case slice the required values
print("average of :",my_list," is ",np.average(my_list))
#average of : [0.1, 0.5, 1] is 0.5333333333333333
#average of : [1.3, 1.4, 1.8] is 1.5
#average of : [1.8, 0.9, 2] is 1.5666666666666667
我有 4 个列表,其中包含 UNIX 中的时间数据和相应的速度。一组比另一组大。我想在较小列表的每个匹配时间戳处找到较大列表的找到值前后几个值的平均速度。
t1 = [2, 5, 7]
t2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
v1 = [0.5, 1, 0.7]
v2 = [0.1, 0.5, 1, 1.3, 1.4, 1.8, 0.9, 2, 1.5, 1.2]
所以如果 t1 和 t2 匹配,我想得到那个时间之前和之后的 x 值的平均速度。
假设 x = 1 在这种情况下,它应该给我 (0.1, 0.5, 1) (1.3, 1.4, 1.8) 和 (1.8, 0.9, 2)
的平均值尝试
import numpy as np
for num in t1: #for each value in t1
try:
match_index=t2.index(num) #check if match exists
except:
match_index=-1 #otherwise set it to -1
if(match_index!=-1): #if match was found
my_list=[] #make an empty list
if(match_index==0): #if index was 0, then nearby 3 elements can't be found, only 2 can
my_list=v2[:match_index+2]
elif(match_index==len(v2)-1): #similarly if index was for last element
my_list=v2[match_index-1:]
else:
my_list=v2[match_index-1:match_index+2] #normal case slice the required values
print("average of :",my_list," is ",np.average(my_list))
#average of : [0.1, 0.5, 1] is 0.5333333333333333
#average of : [1.3, 1.4, 1.8] is 1.5
#average of : [1.8, 0.9, 2] is 1.5666666666666667