2012-10-02 29 views
2

我正在處理某些數據存儲。但是,前處理之後,數據是這樣的,例如:在單個輸入上合併數據

-1|news.cnet.com|Technology News - CNET News|-1|-1 
-1|news.google.com|Google News|-1|-1 
-1|www.bbc.co.uk|BBC News - Home|-1|-1 
-1|www.cnn.com|CNN.com|-1|-1 
-1|www.news.com.au|News.com.au|-1|-1 
1|news.google.com|-1|2|5,156,672 
2|www.cnn.com|-1|71|325,362 
3|www.news.com.au|-1|569|74,584 
4|www.bbc.co.uk|-1|49|442,302 
5|news.cnet.com|-1|107|187,705 

的格式是這樣INDEX|URL|TITLE|RANK|SLI。 值-1指示該列沒有特定的值。 可能有重複條目與URL相同,合併它們都會完成記錄。

是否有一個巧妙的技巧和提示,快速將這些記錄合併爲一個完整的?我不想迭代和循環重複所有行來找到重複的併合並。

編輯: 的預期輸出是這樣的:

1|news.google.com|Google News|2|5,156,672 
2|www.cnn.com|CNN.com|71|325,362 
3|www.news.com.au|News.com.au|569|74,584 
4|www.bbc.co.uk|BBC News - Home|49|442,302 
5|news.cnet.com|Technology News - CNET News|107|187,705 

編輯2: 通過使用熊貓,作爲root以下建議,我能合併的數據列:

from pandas import * 

frame = read_csv(r'data.txt', sep='|', names=['index', 'url', 'title', 'rank', 'sli']) 
mask = frame['index'].map(lambda x: x > 0) 

frame1 = frame[mask].set_index('url') 
frame2 = frame[~mask].set_index('url') 

frame1.title = frame2.title 
frame1.set_index('index') 
print frame1 

但是,有沒有使用任何第三方庫的快速解決方案?

+1

你怎麼想它合併??你能發佈預期的產量嗎? –

+0

對不起,我忘了。我已經更新了期待的輸出。謝謝! –

回答

3

您可以將數據加載到pandasDataFrame並對其進行處理。

from pandas import * 

In [360]: frame=read_csv(r'C:\Python26\test.csv',sep='|', names=['index', 'url', 'title','rank','sli']) 

In [361]: print frame 
    index    url      title rank  sli 
0  -1 news.cnet.com Technology News - CNET News -1   -1 
1  -1 news.google.com     Google News -1   -1 
2  -1 www.bbc.co.uk    BBC News - Home -1   -1 
3  -1  www.cnn.com      CNN.com -1   -1 
4  -1 www.news.com.au     News.com.au -1   -1 
5  1 news.google.com       -1  2 5,156,672 
6  2  www.cnn.com       -1 71 325,362 
7  3 www.news.com.au       -1 569  74,584 
8  4 www.bbc.co.uk       -1 49 442,302 
9  5 news.cnet.com       -1 107 187,705 

In [362]: mask = frame['index'].map(lambda x: x>0) 

In [363]: frame = frame[mask] 

In [364]: print frame 
    index    url title rank  sli 
5  1 news.google.com -1  2 5,156,672 
6  2  www.cnn.com -1 71 325,362 
7  3 www.news.com.au -1 569  74,584 
8  4 www.bbc.co.uk -1 49 442,302 
9  5 news.cnet.com -1 107 187,705 

,如果您有進一步的重複,使用:

df.drop_duplicates() 

此外,請注意您從index扔下dublicates後就可以 「重新索引」:

In [372]: print frame.set_index('index') 
        url title rank  sli 
index           
1  news.google.com -1  2 5,156,672 
2   www.cnn.com -1 71 325,362 
3  www.news.com.au -1 569  74,584 
4  www.bbc.co.uk -1 49 442,302 
5  news.cnet.com -1 107 187,705 
+0

你也可以發佈輸出,並加載數據的過程,這看起來很棒... – Oz123

+1

@ Oz123 - 更新了答案。 – root

+0

ay karamba!一個非常好的答案!給你一個+1。如果我能,我會給你另一個使用IPython的+1! – Oz123

相關問題