我正在处理天文数据,需要帮助对其进行总结。
我的数据包含约 10,000 行,其中每行代表一个系统。
输入文件是制表符分隔的,如下所示: exo 系统行星计数
0 1
0 0
3 4
0 1
2 5
0 0
请注意,系外行星数量通常为 0 或 1,但并非总是如此。
每条线代表一个系统,有两列,一列是在该系统中发现的系外行星,一列是发现的行星总数。
我需要这样通过增加 sys_planet_count 汇总的数据:
system_planet_count exo system_hits system_misses
5 3500 3000 1000
6 4500 4000 1500
exo 行星的数量必须大于或等于 system_hits,因为每个系统可能只有一个或多个 exo 行星,这取决于。
system_planet_count 是表的组织方式。
对于与特定 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) + '\')
输入示例:
外星人 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')
关于python - 如何在 Python 超过 10,000 行的文件中计算每个系统的系外行星?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35393290/