2014-12-05 71 views
0

我试图用以下Python代码从CSV文件绘制图表;从字典中计算和绘制年份的增长率

import csv 
import matplotlib.pyplot as plt 

def population_dict(filename): 
    """ 
    Reads the population from a CSV file, containing 
    years in column 2 and population/1000 in column 3. 

    @param filename: the filename to read the data from 
    @return dictionary containing year -> population 
    """ 
    dictionary = {} 
    with open(filename, 'r') as f: 
     reader = csv.reader(f) 
     f.next() 
     for row in reader: 
      dictionary[row[2]] = row[3] 
      return dictionary 

      dict_for_plot = population_dict('population.csv') 

      def plot_dict(dict_for_plot): 

       x_list = [] 
       y_list = [] 
       for data in dict_for_plot: 
        x = data 
        y = dict_for_plot[data] 
        x_list.append(x) 
        y_list.append(y) 
        plt.plot(x_list, y_list, 'ro') 
        plt.ylabel('population') 
        plt.xlabel('year') 
        plt.show() 

        plot_dict(dict_for_plot) 

        def grow_rate(data_dict): 
# fill lists 
growth_rates = [] 
x_list = [] 
y_list = [] 
for data in data_dict: 
    x = data 
    y = data_dict[data] 
    x_list.append(x) 
    y_list.append(y) 

# calc grow_rate 
for i in range(0, len(y_list)-1): 
    var = float(y_list[i+1]) - float(y_list[i]) 
    var = var/y_list[i] 
    print var 
    growth_rates.append(var) 

# growth_rate_dict = dict(zip(years, growth_rates)) 


grow_rate(dict_for_plot) 

不过,我对这段代码执行

Traceback (most recent call last): 
File "/home/jharvard/Desktop/pyplot.py", line 71, in <module> 
grow_rate(dict_for_plot) 
File "/home/jharvard/Desktop/pyplot.py", line 64, in grow_rate 
var = var/y_list[i] 
TypeError: unsupported operand type(s) for /: 'float' and 'str' 

我一直在尝试不同的方法来施放y_list变量中获得一个相当奇怪的错误。例如;铸造一个int。

我该如何解决这个问题,以便通过这些年来获得增长率的百分比来绘制这个图。

+2

你试过'var/float(y_list [i])'? – ssm 2014-12-05 09:31:21

+0

嗨@ssm,谢谢你的回答。你已经解决了我的问题,我错过了包括我的语法中的float。也许你想添加一个解答这个问题的答案?它解决了我的问题。 – MichaelP 2014-12-05 09:34:53

回答

1

由于CSV文件是文本文件,因此您需要将它们转换为数字。它容易纠正语法错误。只需使用

var/float(y_list[i]) 

即使是摆脱了语法错误,有一个小错误,这是一个小更难以发现,这可能结果在某些情况下不正确的结果。主要原因是字典未订购。即x和y值不以任何方式排序。您的程序的缩进在我的电脑上似乎有点偏离,所以我无法完全遵循它。但它的要点似乎是,您是从一个文件(x和y值)获得的值,然后找到序列

var[i] = (y[i+1] - y[i])/y[i]

不幸的是,你的y_list[i]可能无法在相同的序列中CSV文件,因为它正在从字典中填充。

在你做的部分:

for row in reader: 
     dictionary[row[2]] = row[3] 

它仅仅是更好的做

x, y = zip(*[ (float(row[2]), float(row[3])) for row in reader]) 
x, y = map(numpy.array, [x, y]) 
return x, y 

或像这样维护秩序......

然后,numpy的阵列有更有效地处理您的问题的方法。你可以简单地做:

growth_rates = numpy.diff(y)/y[:-1] 

希望这会有所帮助。如果您有任何问题,请告诉我。

最后,如果你选择了Numpy路线,我会强烈推荐它自己的csv阅读器。看看这里:http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html