Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对特定列中的数字求和?_Python_File_Numbers_Sum_Multiple Columns - Fatal编程技术网

Python 如何对特定列中的数字求和?

Python 如何对特定列中的数字求和?,python,file,numbers,sum,multiple-columns,Python,File,Numbers,Sum,Multiple Columns,我正在尝试制作一个程序,可以从一个文本文件中对一列中的所有数字求和 这里有一个链接,显示文本文件的前5行 例如,我如何对FXM列中的所有数字求和 我真的很感谢你的帮助 也许您最好使用CSV excel文件来存储此类数据。然后您需要打开文件并像这样读取文件 import csv file = open(path, newline='') read = csv.reader(file) header = next(reader) data = [] for row in reader: #T

我正在尝试制作一个程序,可以从一个文本文件中对一列中的所有数字求和

这里有一个链接,显示文本文件的前5行

例如,我如何对FXM列中的所有数字求和


我真的很感谢你的帮助

也许您最好使用CSV excel文件来存储此类数据。然后您需要打开文件并像这样读取文件

import csv 
file = open(path, newline='')
read = csv.reader(file)

header = next(reader)

data = []
for row in reader: #This includes all your rows
    #Here you specify the data types of all of your rows
您将需要进行一些调整,以使此操作适用于列

然后,根据所需列的索引,您可以编写一个循环来迭代列表中的所有元素

ex.
sum=0
for element in column[6]:
     sum+=element #Assuming that you already specified in the previous loop 
                  #that these elements were floats

这里似乎有一个以制表符分隔的文本文件。这是一个简单的解决方案函数,并附有使用示例

import csv
def colsum(filename, delimiter, colname):
    reader   = csv.reader(open(filename), delimiter='\t')
    headers  = next(reader)
    entries  = [ x for x in reader ]
    index    = headers.index(colname)
    result   = sum( [ float(entry[index]) for entry in entries ] )
    return(result)

def main():
    print(colsum('test_data.txt', '\t', 'DD06'))

if __name__ == '__main__': main()

那不是文本文件…@odin fossil这是文本文件吗?在文件中有这样的表格设置吗?或者它是另一种类型的文件?我知道它不是文本文件。这只是前几行的屏幕截图,以举例说明它的外观。@odinfossli:是否可以粘贴一个小的示例文本文件(例如前三行)。您知道,由于格式上的微小差异,解析可能会失败。您的文本文件是什么格式?如果是CSV,您可以查看如何读取该文件。然后为文件的每一行读取正确的列,并汇总值。