如何使用Python分析cvs文件?

时间:2017-08-17 23:43:32

标签: python

我是编程的初学者,我现在正在尝试研究如何获取csv文件中元素的平均值。这是csv文件的内容:

enter image description here

这是我的代码:

import csv
suburbs_average = {'North':0,'South':0,'East':0,'West':0}
suburbs_count = {'North':0,'South':0,'East':0,'West':0}
csvfile = open("ps1_3_data.csv")
csv_reader = csv.reader(csvfile, delimiter=',')

for row in csv_reader:
   print (row[0],float(row[1]))


print(suburbs_average)

我花了一整天的时间试图弄清楚如何计算每个郊区的平均值(东,北......)。在计算之前我需要将同一个郊区排在一起吗?有人可以帮我这个吗?提前致谢。欢呼声。

3 个答案:

答案 0 :(得分:0)

您可以使用类似openpyxl的内容,它会以特定格式读取excel文件。如果你试图将项目之间的数据分开,我建议拆分项目并将它们存储在HashMap或类似的东西中。例如,对于每一行,通过逗号分割字符串,这样你就有两个独立的数据点,然后从那里开始。

答案 1 :(得分:0)

鉴于您图片的子集非常有限:

li=[('East',10.0),('West',5.0),('East',5.0),('West',2.0),('West',1.0)]

您可以使用'West, East, etc键创建列表字典:

di={}
for d, n in li:
    di.setdefault(d, []).append(n)

>>> di
{'West': [5.0, 2.0, 1.0], 'East': [10.0, 5.0]}

然后加上并除以条目数:

>>> {d:sum(l)/len(l) for d, l in di.items()}
{'West': 2.6666666666666665, 'East': 7.5}

答案 2 :(得分:0)

我真的很喜欢使用标准库,所以我认为你也应该坚持使用它,这样你就可以在安装模块之前理解基础实现。

csv模块是标准库的一部分,阅读docs将帮助您了解每个模块在寻找解决方案时的能力。鉴于您的问题,我会执行以下操作:

  

遍历csv.reader()对象并将值放入dict() s,然后对其进行平均。

import csv

# keep track of each time we see one
count = {'North': 0,
         'South': 0,
         'East': 0,
         'West': 0}

# store the associated values each time we see one
avg = {'North': [],
       'South': [],
       'East': [],
       'West': []}

# get rid of newline if not Py3
with open("ps1_3_data.csv", 'r', newline='') as f: 
    r = csv.reader(f, delimiter=',')
    # assumes you dont have a header row
    # if you do, uncomment the line below this
    # header = next(r)
    for row in r:
        # increment count each time we see one
        count[row[0]] += 1
        # add to the suburbs list of values
        avg[row[0]].append(float(row[1])

# here we replace the lists with a single value
# goes from {'North': [15.0, 10.0, 10.0]}
# to {'North': 11.6666...}
for suburb in avg:
    avg[suburb] = (sum(avg[suburb])/len(avg[suburb])

我用提供的测试数据制作了一个CSV:

>>> import csv
>>> temp = r'C:\Users\Paul\Desktop\temp.csv'
>>> count = {'North': 0,
     'South': 0,
     'East': 0,
     'West': 0}
>>> avg = {'North': [],
     'South': [],
     'East': [],
     'West': []}
>>> with open(temp, 'r', newline = '') as f:
    r = csv.reader(f, delimiter=',')
    for row in r:
        count[row[0]] += 1
        avg[row[0]].append(float(row[1]))


>>> count
{'North': 3, 'South': 4, 'East': 5, 'West': 5}
>>> avg
{'North': [15.0, 10.0, 10.0], 'South': [10.0, 5.0, 5.0, 10.0], 'East': [10.0, 5.0, 10.0, 5.0, 10.0], 'West': [20.0, 15.0, 15.0, 20.0, 5.0]}
>>> for suburb in avg:
    avg[suburb] = (sum(avg[suburb])/len(avg[suburb]))


>>> avg
{'North': 11.666666666666666, 'South': 7.5, 'East': 8.0, 'West': 15.0}
>>>