如何在 Python 中超过 10,000 行的文件中计算每个系统的系外行星?

How do I count exoplanets per system in a file with over 10,000 lines in Python?

我正在处理天文数据,需要帮助对其进行总结。

我的数据包含约 10,000 行,其中每行代表一个系统。

输入文件是用制表符分隔的,如下所示: exo sys_planet_count

0   1   
0   0   
3   4   
0   1   
2   5   
0   0   

请注意,系外行星数量通常为 0 或 1,但并非总是如此。

每一行代表一个系统并且有两列,一列是在该系统中发现的exo_planets,一列是发现的行星总数。

我需要这样汇总的数据,增加sys_planet_count:

system_planet_count exo system_hits system_misses

5 3500 3000 1000
6 4500 4000 1500

系外行星的数量必须大于或等于system_hits,因为每个系统可能只有一个或多个系外行星,这取决于。

system_planet_count 是 table 的组织方式。

对于匹配特定 system_planet_count 的每一行(系统),它会添加找到的 exos 数量。 如果发现外星人,它会将 +1 添加到 system_hits 类别,因为该行发现了外星人行星,很成功。 如果在该行中没有找到 exos,它会在 system_misses 类别中添加一个,因为行星中没有行。

请注意,system_misses 和 system_hits 类别特定于 system_planet 计数,即 3000 和 1000 用于 system_planet_count 5,但 4000 和 1500 用于 system_planet_count 共 6

问题是数据没有按 sys_planet_counts 的升序排列。

为了总结数据,我想出了以下代码。我应该怎么做才能快速总结数据而不需要 10 或 15 分钟?

我正在考虑使用字典,因为每个 system_planet_count 都可以充当键

while open('data.txt','r') as input:
    for line in input:
        system_planet_count = 0
        exo_count = 0
        system_hits = 0
        system_misses = 0

        foo
    output.write(str(system_planet_count) + '\t' + str(exo_count) + '\t' + str(system_hits) + '\t' + str(system_misses) + '\')

输入示例:

exo sys_planet_count

 2 1
 0 1
 1 1
 0 5
 1 5
 0 5
 0 5
 2 5
 0 5
 0 4

输出:

system_planet_count exo system_hits system_misses

 1 3 2 1
 4 0 0 1
 5 3 2 4

这应该可以完成您想要的摘要:

from collections import defaultdict

def summarize(file_name):
    exo, hit, miss = 0, 1, 2  # indexes of according counts
    d = defaultdict(lambda: [0, 0, 0])  # keep all counts for each type of system
    with open(file_name, 'r') as input:
        for line in input:
            exos, planets = map(int, line.strip().split())  # split, cast to int
            if exos:
                d[planets][exo] += exos
                d[planets][hit] += 1
            else:
                d[planets][miss] += 1

    for key in sorted(d.keys()):
        print('{} {} {} {}'.format(key, d[key][exo], d[key][hit], d[key][miss]))

summarize('data.txt')