2014-12-05 34 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