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: 通过使用 Panda,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

但是,有没有使用任何第三方库的快速方法?

4

1 回答 1

3

您可以将数据加载到熊猫 DataFrame中并进行处理。

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您可以“重新索引”:

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
于 2012-10-02T06:59:02.963 回答