【问题标题】:Want to loop file by file in a directory of weather data, then loop through an entire month (day by day) saving precipitation data?想要在天气数据目录中逐个文件循环,然后循环整个月(逐日)保存降水数据?
【发布时间】:2018-04-12 21:18:08
【问题描述】:

我正在尝试制作一个脚本来读取一组 CSV 文件,这些文件存储在我的数据目录中,称为“数据库”,存储在我的桌面上。在这些 CSV 文件中是天气数据,CSV 的最后一个列表索引 16 是降水量,我试图获取并计算每个站的月总降水量。每个站包含 12 个月的天气数据,CSV 中的最后一个索引是降水量。最后,我想输出一个 CSV 文件,其中包含 48 行(12 个月 x 4 个站点),包括站点 ID、月份编号和该站点该月的总降水量。

这是我目前所拥有的:

import glob

files = glob.glob("database/*.csv")

def totalPercip(list):
    total = 0
    # iterate through the lists of month, each time getting the 16th element, preciptation
    for i in list:
# getting only the 16th index for each day for specific month list
# not sure if this is correct
        total = i[16]
        print(total)


# loop through it one file at a file
for i in files:
    # opening one of the files in the pre-made directory, and reading out the contents
    f = open(i,'r')
    # loop through each line of said specific file at current iteration
    for j in f.readlines():
        # save all those lines into one variable called list
        list = [j]
    # past list as an argument into totalPercip function
    totalPercip(list)
# stuck here, not sure how to get totalPercip to work and get the 16th index

这是我的文件夹的样子:

这是 CSV 文件的样子,试图获取最后一个索引:

所以我正在尝试创建一个函数来计算给定一个月的数据的总降水量。由于它接受了一个月的天气数据,我想让它返回一个包含当月降水总量的浮点值。我知道我需要遍历列表中的所有元素(每月的每一天),然后用逗号分隔每个元素,然后进行内部循环以将当月的总数相加。只是不完全确定如何去做以及到目前为止我做错了什么。

【问题讨论】:

  • 请不要发布数据或代码的图像,只需将其复制并粘贴到您的问题中,作为代码格式的文本 - 仅粘贴最少量,足以说明您遇到的问题。 minimal reproducible example
  • 您是否遇到错误?在询问有关产生异常的代码的问题时,请在问题中包含完整的 Traceback。
  • 使用csv module 使阅读 .csv 文件变得容易。

标签: python csv


【解决方案1】:

此代码应该适用于您的 totalPercip() 函数。您的错误是 1)您没有增加 total 变量,并且每个循环将其分配给不同的新值,以及 2)i[16] 可能会给您一个 List ouf of bounds 异常,因为 i[0] = 1st index, i[1] = 2nd index..., i[15] = 16th index

def totalPercip(list):
    total = 0
    for i in list:
        percip = float(i[15].replace(',','')) #16th index
        total += percip 

    return total

我还建议您不要使用 list 作为变量名,因为它会掩盖以该名称调用的内置 python 函数。

希望这会有所帮助!

【讨论】:

  • 告诉我类型错误:+= 不支持的操作数类型:'int' 和 'str'
  • 我的错,索引是一个字符串,在增加 total 变量之前需要转换为整数。编辑了我的答案。
  • 现在我得到:ValueError: invalid literal for int() with base 10: ','
  • 哦,是的,因为您的某些数据包含小数,您可能应该使用float(i[15]) 而不是int(i[15])
  • 抱歉重播晚了,但现在它说 ValueError: could not convert string to float: ,最后的“,”很重要。不知道如何删除它。
猜你喜欢
  • 2020-12-17
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 2022-12-17
  • 1970-01-01
相关资源
最近更新 更多