[英]How to find the sum of a column from a csv file using vanilla python (without using numpy or pandas)?
I have tried a lot of different things to do this without using numpy or pandas.在不使用 numpy 或 pandas 的情况下,我尝试了很多不同的方法来做到这一点。 I have looked at similar posts, but I just can't get anything to work.
我看过类似的帖子,但我什么也做不了。 How can I solve this?
我该如何解决这个问题?
The reason I want to do this is that I have read that I should avoid using packages whilst learning vanilla python.我想这样做的原因是我读过我应该避免在学习 vanilla python 时使用包。 ( https://chrisconlan.com/learning-python-without-library-overload/ )
( https://chrisconlan.com/learning-python-without-library-overload/ )
import csv
import numpy as np
import os
with open('ams_data.csv') as ams_data:
read_csv = csv.reader(ams_data, delimiter=';')
data = list(read_csv)
x_dagar, y = (len(data) - 1) // 24, np.genfromtxt(open('ams_data.csv', 'rb'), delimiter=';', skip_header = 1)
A = np.delete(y, [0, 1], 1)
print(sum(A))
I get the output I want, however I do not want to use 'import numpy as np', or any other package I have to download, how can I change my code for it to do the same thing as it does now.我得到了我想要的 output,但是我不想使用“将 numpy 作为 np 导入”或任何其他 package 我现在必须做同样的事情来更改我的代码。 Which would be summing the float of the last element in every row, but the first, of my csv file.
这将把我的 csv 文件中每一行中最后一个元素的浮点数相加,但第一个元素。
Trying to solve this myself I have gotten;我自己试图解决这个问题;
[[1.152]
[0.91 ]
[0.773]
[0.766]
[0.898]
[0.628]
[1.76 ]
[2.58 ]
[2.026]
[2.774]
[1.746]
[1.089]
[0.884]
[0.816]
[0.847]]
but without the last brackets [[1.152]+... + [0.847]] sorrounding all the numbers.但没有最后一个括号 [[1.152]+... + [0.847]] 环绕所有数字。 Which in my belief is what I have to do to get the sum?
在我看来,我必须做什么才能得到总和? Any help would be much appreciated: :D
任何帮助将不胜感激::D
As far as I understand, you want to read the CSV file without Numpy or Pandas, and then compute the sum of all columns but the first two (it seems), starting from the second row.据我了解,您想阅读没有 Numpy 或 Pandas 的 CSV 文件,然后从第二行开始计算除前两列(似乎)之外的所有列的总和。 You could do this, using list comprehensions:
你可以这样做,使用列表推导:
with open('ams_data.csv') as ams_data:
lines = ams_data.readlines()
data = [[float(elt) for elt in line.split(";")] for line in lines]
result = [sum(row[2:]) for row in data[1:]]
The conversion to float assumes that all elements in your CSV file are floats.转换为浮点数假定 CSV 文件中的所有元素都是浮点数。 The first row is excluded from the sum with
data[1:]
, and the first two columns are excluded with row[2:]
.使用
data[1:]
从总和中排除第一行,使用row[2:]
排除前两列。 I guess you can adapt from here.我想你可以从这里适应。
Try doing this -尝试这样做 -
my_list = [row[-1] for row in read_csv]
print(sum([float(i) for i in my_list[1:]]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.