将数据表复制到Python列表后,我必须将表2中的值拆分回独立系列。总的来说,您可以跳过将这些值合并到单个表格Table2中的步骤。
解决此问题的关键是编写一个简单的类,实现__getitem__
,采用一个键参数并返回相应的值。例如,对于常规的Python字典,则__getitem__
会返回与该键完全匹配的字典条目,如果不匹配则返回KeyError。在你的情况,我实现__getitem__
只返回一个带有条目的时间戳从给定的时间戳的最小差异的条目,在这条线:
closest = min(self.data, key=lambda x: abs(x[0]-keyts))
(左作为一个练习OP - 如何处理的情况下密钥恰好落在两个条目之间)。如果您需要调整查找逻辑,只需更改__getitem__
的实现 - 代码中的其他内容将保持不变。
这里是我的示例实现:
# t1 and t2 are lists of tab-delimited strings copy-pasted
# from the OP's spreadsheet
TAB = '\t'
t1data = [t.split(TAB) for t in t1]
t2data = [t.split(TAB) for t in t2]
# split each parameter into individual time,value pairs
readings = {'A':[], 'B':[], 'C':[]}
for parm in "ABC":
for trec in t2data:
t,a,b,c = trec
t = int(t)
if a: readings['A'].append((t,int(a)))
if b: readings['B'].append((t,int(b)))
if c: readings['C'].append((t,int(c)))
# define class for retrieving value with "closest" key if
# there is not an exact match
class LookupClosest(object):
def __init__(self, pairs):
self.data = pairs
def __getitem__(self, key):
# implement logic here to find closest matching item in series
# TODO - what if key is exactly between two different values?
closest = min(self.data, key=lambda x: abs(x[0]-key))
return closest[1]
# convert each data series to LookupClosest
for key in "ABC":
readings[key] = LookupClosest(readings[key])
# extract and display data
for vals in t1data:
t = int(vals[0])
gps = vals[1]
a = readings['A'][t]
b = readings['B'][t]
c = readings['C'][t]
rec = t,gps,a,b,c
print rec
打印:(我修改了表1的数据,让你可以告诉从一个记录到下的区别):堆栈溢出
(1, 'x01', 1, 10, 44)
(10, 'x10', 2, 11, 47)
(21, 'x21', 4, 12, 45)
(30, 'x30', 3, 12, 44)
(41, 'x41', 4, 12, 47)
(52, 'x52', 2, 10, 48)
欢迎!这不是很明显,你想要什么,你有什么,以及你期望如何与你所做的一切达成目标。请**举例输入和输出**需要和*解释*你一直在试图做到这一点。请避免链接到异地资源。 – Veedrac 2014-09-28 08:14:29