从字典中计算和绘制年增长率

时间:2014-12-05 08:52:56

标签: python dictionary matplotlib

我正在尝试使用以下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。

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

1 个答案:

答案 0 :(得分: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