【问题标题】:My code returns a list full of zeros when it should have values我的代码在它应该有值时返回一个充满零的列表
【发布时间】:2023-03-09 05:10:02
【问题描述】:

正如问题所述,我编写了一段代码来查找大型数据集中多行数据的平均值。由于某种原因,代码现在只返回一个包含零的元组列表,它曾经在对较小的数据位进行测试时显示值,但在改进代码后它现在不起作用。我似乎看不到我在哪里弄坏了东西,谢谢你的帮助。

我在下面粘贴了整个函数,我似乎看不到错误。我的猜测是它与循环有关,但我不明白哪里有问题。

def makeAverageList(input,col1=1,col2=2,monthavg=200):
    f = open(input + ".txt", "r")
    col1avg = []
    col2avg = []
    points = []
    length = len(f.readlines())
    count = 1
    maxcount = float(length/monthavg)
    while True:
        lines = list(islice(f, monthavg))
        col1list = []
        col2list = []
        linelist = []
        for i in lines:
            linelist.append(i[1:-2])
        for l in linelist:
            line = []
            line = l.split(",")
            col1list.append(float(line[col1]))
            col2list.append(float(line[col2]))
        A = float(sum(col1list))
        col1avg.append(float(A/monthavg))
        B = float(sum(col2list))
        col2avg.append(float(B/monthavg))
        count = count + 1
        if not count < maxcount:
            break
    for z in range(len(col1avg)):
        P = (float(col1avg[z]), float(col2avg[z]))
        points.append(P)
    return points

print(makeAverageList("data.monthly_nh_clean"))

[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]

数据集是多行这样的值:

,1850.08,-0.844,-0.921,-0.747,-1.036,-0.652,-1.374,-0.314,-1.051,-0.635,-1.413,-0.274

,1850.17,-0.053,-0.119,0.032,-0.254,0.148,-0.621,0.515,-0.270,0.166,-0.661,0.556

,1850.25,-0.699,-0.794,-0.632,-0.891,-0.508,-1.124,-0.274,-0.910,-0.495,-1.174,-0.229

在代码中,我对其进行格式化、拆分并从中获取值。我不明白它为什么停止工作。

【问题讨论】:

  • Python 2.7 还是 3?例如,您计算maxcount = float(length/monthavg)。如果您在 Python 2.7 中并且 lengthmonthavg 是整数,那么它们的分数将再次成为整数!在这种情况下,之后采取浮动将无济于事。这可能是个问题吗?
  • 否则,您能否提供一些示例性输入数据?
  • 它必须是python3,因为print().
  • 欢迎哈姆扎!你有调试器介入吗?你学到了什么?
  • 感谢 cmets,我正在运行 python 3.7。 Michele 我真的不知道如何使用调试器。

标签: python function loops tuples data-analysis


【解决方案1】:

您只能对打开的文件进行一次迭代。第一次,你消耗所有的输入是为了确定行数。第二次,您尝试读取 while 循环中的行,该文件已被使用,并且没有给出任何结果,因此是一个空列表 linelist

为了简化所有,你不需要maxcount,但检查空的col1list

def makeAverageList(input, col1=1, col2=2, monthavg=200):
    points = []
    with open(input + ".txt") as lines:
        while True:
            col1list = []
            col2list = []
            for line in islice(lines, monthavg):
                line = line.strip(',').split(",")
                col1list.append(float(line[col1]))
                col2list.append(float(line[col2]))
            if not col1list:
                # end of file
                break
            avg1 = sum(col1list) / len(col1list)
            avg2 = sum(col2list) / len(col2list)
            points.append((avg1, avg2))
    return points

【讨论】:

  • 啊我不知道你只能遍历文件一次,谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 2018-03-04
  • 2015-02-12
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多