Python CSV Reader For Loop读取行,但未到达Fi的末尾

2024-10-01 15:42:23 发布

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

我开发了一个函数,用于汇总文件中给定的每个给定队列的总人口。此函数当前被使用两次。一次是得到总[实际]人口,一次是得到“病例”总数。 我遇到了一个问题,函数没有读取“cases”文件的末尾。我实现了一个行计数器,它打印遍历的行数。population file counter输出为933,case file counter输出为911,这意味着它没有读取最后22个case。有人知道为什么会这样吗?在

以下是我定义的函数:

def newPopCount(filename, fileheader):
    rowCount = 0  # Row counter
    import csv
    popholder = []
    cohorts = []
    print (len(fileheader))
    for i in range(3, len(fileheader)):
        cohorts.append(fileheader[i])
    for i in range(len(cohorts)):
        popholder.append(0)

    popcsv = open(filename, 'r', newline = '')
    popreader = csv.reader(popcsv, delimiter = ',')

    for row in popreader:
        rowCount += 1
        counter = 0
        if row[0] == fileheader[0]:
            continue
        else:
            for i in range(3, len(fileheader)):
                popholder[counter] += int(row[i])
                counter += 1

    popcsv.close()  

    print (rowCount)  # Print row counter
    return popholder

顺便说一句:fileheader是从另一个函数获得的,就像它听起来一样-文件的头。另外,索引从3开始,因为文件中的第一个条目是zipcode、x坐标和y坐标。在

如果有人有任何想法请分享!在

这是一个新的案例文件,它用逗号正确地分隔了数据。还有第二个文件,其中包含数据原始状态的示例。这些数据在main函数调用中聚合,该函数生成我们实际讨论的文件:Cases

我还决定包括代码,我用它来获取标题。我通常通过设置一个等于它的变量来调用它:thisHeader = getHeader('Cases.csv'),然后调用另一个函数caseRecord = newPopCount('Cases.csv', thisHeader)

以下是getHeader函数:

^{pr2}$

再次感谢您的关注!在


Tags: 文件csv数据函数inforlencounter
3条回答

这不是您问题的答案,所以我将其改为CW,但是您可能有兴趣查看pandas库。它使处理表格数据比其他方式有趣得多。在

首先读入数据(我在这里使用您的NewCaseFile,它似乎是用逗号分隔的,所以我将其命名为ncf.csv):

>>> import pandas as pd
>>> df = pd.read_csv("ncf.csv")
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 932 entries, 0 to 931
Data columns (total 9 columns):
zcta       932  non-null values
xcoord     932  non-null values
ycoord     932  non-null values
m5064      932  non-null values
m6574      932  non-null values
m75plus    932  non-null values
f5064      932  non-null values
f6574      932  non-null values
f75plus    932  non-null values
dtypes: float64(1), int64(8)
>>> df.head() # look at the start of the frame
    zcta    xcoord   ycoord  m5064  m6574  m75plus  f5064  f6574  f75plus
0  51062  211253.4  4733175      0      0        1      0      0        0
1  51011  212255.6  4757939      0      0        1      0      0        0
2  51109  215303.5  4721048      0      1        7      0      1        2
3  51001  215651.1  4746655      1      0        4      0      1        0
4  51103  216887.7  4713568      4      9       28      1      1        8

使用x、y、zip列作为索引,并在population列中求和:

^{pr2}$

按列汇总:

>>> df.sum()
m5064       981
m6574      1243
m75plus    2845
f5064      1355
f6574      1390
f75plus    1938
total      9752
dtype: int64

等等。特别是,它使许多原本简单易懂但在实践中很烦人的转换变得容易得多。例如:

>>> df = pd.read_csv("ncf.csv")
>>> d2 = pd.melt(df, id_vars=list(df.columns[:3]))
>>> d2["sex"] = d2["variable"].str[:1]
>>> d2["age_lower"] = d2["variable"].str[1:3].astype(float)
>>> d2["age_upper"] = d2["variable"].str[3:].replace("plus", 100).astype(float)
>>> del d2["variable"]
>>> d2.rename(columns={"value": "count"}, inplace=True)

给出:

>>> d2.head()
    zcta    xcoord   ycoord  count sex  age_lower  age_upper
0  51062  211253.4  4733175      0   m         50         64
1  51011  212255.6  4757939      0   m         50         64
2  51109  215303.5  4721048      0   m         50         64
3  51001  215651.1  4746655      1   m         50         64
4  51103  216887.7  4713568      4   m         50         64
>>> d2.groupby("sex")["count"].sum()
sex
f      4683
m      5069
Name: count, dtype: int64

等等。在

首先感谢大家考虑到他的问题并试图帮助我。在回答@abarnert的问题时发现,我在这个聚合文件(NewCaseFile.csv)创建之后忘记关闭它。因此,在添加.close()语句之后,一切都开始正常工作。谢谢大家花时间来研究我的问题。在

我下载了你的要旨并保存为cases.tsv。在

然后,我修改了您的newPopCount,在open之后执行popcsv.readline(),并将下一行改为使用delimiter='\t',而不是{}。在

然后我用这句话进行了分析:

h = newPopCount('cases.tsv', ['zcta', 'xcoord', 'ycoord', 'm5064', 'm6574', 'm75plus', 'f5064', 'f6574', 'f75plus'])

它打印了932。在

因为有933行,其中一行是头(不计数),这是正确的答案。在

所以,我猜你只是在错误的文件上运行了它,所以你得到了错误的答案。在

你的代码中有一个bug并不是不可能的,你上传的不正确的示例数据正好与这个bug相对应……但这似乎不太可能。如果您能给出实际的文件,以及在该文件上实际运行的代码,以及调用newPopCount函数的代码,那么排除这种可能性应该很简单。在

相关问题 更多 >

    热门问题