繁体   English   中英

如何从 Python 上的文本文件中提取求和数据

[英]How to extract a sum data from a text file on Python

我有一个包含 6 列的文本文件 txt:1.sex (M /F) 2.age 3.height 4.weight 5.-/+ 6.zip code

我需要从这篇文章中找出有多少男性有 - 标志。 (例如:来自 txt 30 M(Male) are - )

所以我只需要最后的数字。

从逻辑上讲,我需要使用 Column1 和 column 5,但我很难在最后得到一个(总和)数字。

这是正文的内容:

M 87  66 133 - 33634
M 17  77 119 - 33625
M 63  57 230 - 33603
F 55  50 249 - 33646
M 45  51 204 - 33675
M 58  49 145 - 33629
F 84  70 215 - 33606
M 50  69 184 - 33647
M 83  60 178 - 33611
M 42  66 262 - 33682
M 33  75 176 + 33634
M 27  48 132 - 33607

我现在得到了结果......,但我想要 M 和阳性。 我怎样才能将其添加到事件中?

f=open('corona.txt','r')
data=f.read()
occurrences=data.count('M')
print('Number of Males that have been tested positive:',occurrences)

您可以像这样拆分行:

occurrences = 0
with open('corona.txt') as f:
    for line in f:
        cells = line.split()
        if cells[0] == "M" and cells[4] == "-":
            occurrences += 1
print("Occurrences of M-:", occurrences)

但最好使用csv模块或pandas进行此类工作。

如果您对文本和柱状数据进行了大量工作,我建议您开始学习pandas

对于此任务,如果您的 csv 每行一条记录并且以空格分隔:

import pandas as pd
d = pd.read_csv('data.txt', 
        names=['Sex', 'Age', 'Height', 'Weight', 'Sign', 'ZIP'], 
        sep=' ', index_col=False)

d[(d.Sex=='M') & (d.Sign=='-')].shape[0] # or
len(d[(d.Sex=='M') & (d.Sign=='-')]) # same result, in this case = 9

Pandas是一个非常广泛的 package。此代码的作用是根据您的 csv 数据构建一个DataFrame ,并为每一列命名。 然后从中选择您的条件Sex == 'M'Sign == '-'每一行,并报告由此找到的记录数。

我建议从这里开始

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM