在Python中,如何计算一个文件中每个系统的系外行星数,该文件有10000多行?

2024-05-16 10:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究天文数据,我需要帮助来总结它

我的数据包含~10000行,每行代表一个系统

输入文件的制表符分隔方式如下: 外部系统行星计数

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

请注意,外行星计数通常是0或1,但并不总是如此

每一行代表一个系统有两列,一列表示在该系统中发现的系外行星,一列表示发现的行星总数

我需要通过增加系统行星计数来总结数据:

系统\u行星\u计数exo系统\u命中系统\u未命中

5 3500 3000 1000
6 4500 4000 1500

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

系统行星计数是表格的组织方式

对于每一行(系统)匹配一个特定的系统行星计数,它加上找到的exo数。 如果发现了系外行星,它会在系统命中分类中加上+1,因为那条线发现了系外行星,一个命中。 如果在该行中没有发现exos,那么它会将一个exos添加到system-u-misses类别中,因为行星中没有行

请注意,系统未命中和系统命中类别特定于该系统行星计数,即系统行星计数为5时为3000和1000,系统行星计数为6时为4000和1500

问题是数据不是按系统计数的升序排列的

为了总结这些数据,我编写了以下代码。我应该怎么做才能在不需要10或15分钟的时间内快速总结数据

我在考虑使用字典,因为每个系统的计数都可以作为键

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) + '\')

输入示例:

外部系统行星计数

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

输出:

系统\u行星\u计数exo系统\u命中系统\u未命中

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

Tags: 数据input系统count方式代表行星外行星
1条回答
网友
1楼 · 发布于 2024-05-16 10:09:07

这将完成您想要的摘要:

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')

相关问题 更多 >