简体   繁体   中英

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. 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. ( 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. Which would be summing the float of the last element in every row, but the first, of my csv file.

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. Which in my belief is what I have to do to get the sum? Any help would be much appreciated: :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. 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. The first row is excluded from the sum with data[1:] , and the first two columns are excluded with 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:]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM