我试图用以下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