我試圖用以下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。
我該如何解決這個問題,以便通過這些年來獲得增長率的百分比來繪製這個圖。
你試過'var/float(y_list [i])'? – ssm 2014-12-05 09:31:21
嗨@ssm,謝謝你的回答。你已經解決了我的問題,我錯過了包括我的語法中的float。也許你想添加一個解答這個問題的答案?它解決了我的問題。 – MichaelP 2014-12-05 09:34:53