我想计算 txt 文件中每一行的缺失发生率。
foo.txt
文件:
1 1 1 1 1 NA # so, Missings: 1
1 1 1 NA 1 1 # so, Missings: 1
1 1 NA 1 1 NA # so, Missings: 2
但我也想获得第一行的元素数量(假设所有行都相等)。
miss = []
with open("foo.txt") as f:
for line in f:
miss.append(line.count("NA"))
>>> miss
[1, 1, 2] # correct
问题是当我尝试确定元素的数量时。我用以下代码做到了这一点:
miss = []
with open("foo.txt") as f:
first_line = f.readline()
elements = first_line.count(" ") # given that values are separated by space
for line in f:
miss.append(line.count("NA"))
>>> (elements + 1)
6 # True, this is correct
>>> miss
[1,2] # misses the first item due to readline() removing lines.`
如何在不删除第一行以进行进一步操作的情况下读取第一行?