2014-09-28 33 views
0

用戶結合2個表格和彙總數據

請問您可以幫忙跟進嗎?

我需要從MySQL數據庫中提取數據並對它們進行聚合。 數據庫中有兩個表格,它們都有不同時間步長的數據。 我現在需要創建一個新表(txt),其中表1的所有數據都與表2數據組合在一起。 我這樣只需要表2的多數coresponding時間見表1

的時間步長的數據進行更好的理解,看到這裏的表的例子: https://www.dropbox.com/s/mo2q0hj72ilx05n/data%20aggregation.xlsx?dl=0

我已經有一個python-代碼提取十六進制數據並生成表2. 我還有一個代碼,它可以生成表1. 我需要現在將兩者結合起來。

非常感謝您的建議!

+1

歡迎!這不是很明顯,你想要什麼,你有什麼,以及你期望如何與你所做的一切達成目標。請**舉例輸入和輸出**需要和*解釋*你一直在試圖做到這一點。請避免鏈接到異地資源。 – Veedrac 2014-09-28 08:14:29

回答

0

將數據表複製到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)