我有包含两列的简单文本文件,都是整数
1 5
1 12
2 5
2 341
2 12
等等..
我需要按第二个值对数据集进行分组,这样输出就可以了。
5 1 2
12 1 2
341 2
现在的问题是该文件非常大,大约 34 Gb,我尝试编写一个 python 脚本将它们分组到一个字典中,其值为整数数组,但仍然需要太长时间。(我想array('i')
在append
.
我现在正计划编写一个猪脚本,我计划在伪分布式 hadoop 机器(一个 Amazon EC3 高内存大型实例)上运行该脚本。
data = load 'Net.txt';
gdata = Group data by $1; // I know it will lead to 5 (1,5) (2,5) but thats okay for this snippet
store gdata into 'res.txt';
我想知道是否有更简单的方法可以做到这一点。
更新: 在内存中保留这么大的文件是没有问题的,在 python 解决方案的情况下,我计划在第一次运行时进行 4 次运行,只有从 1 到 1000 万的第二个 col 值在下一次运行时考虑 1000 万到 2000 万被考虑等等。但事实证明这真的很慢。
pig / hadoop 解决方案很有趣,因为它将所有内容都保存在磁盘上[好吧大部分]。
为了更好地理解这个数据集包含了大约 4500 万 twitter 用户的连接信息,文件中的格式意味着第二个数字给出的用户 ID 在第一个数字之后。
我用过的解决方案:
class AdjDict(dict):
"""
A special Dictionary Class to hold adjecancy list
"""
def __missing__(self, key):
"""
Missing is changed such that when a key is not found an integer array is initialized
"""
self.__setitem__(key,array.array('i'))
return self[key]
Adj= AdjDict()
for line in file("net.txt"):
entry = line.strip().split('\t')
node = int(entry[1])
follower = int(entry[0])
if node < 10 ** 6:
Adj[node].append(follower)
# Code for writting Adj matrix to the file: