gpt4 book ai didi

python - 合并单个输入的数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:43 25 4
gpt4 key购买 nike

我正在处理一些数据存储。但是,经过预处理后,数据是这样的,例如:

-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

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

最佳答案

您可以将数据加载到 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 中删除重复项后,您可以“重新编制索引”:

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

关于python - 合并单个输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12685748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com