【发布时间】:2020-03-18 17:28:41
【问题描述】:
所以我正在阅读 Python Crash Course 这本书,其中一个练习是查找自定义 CSV 文件并使用 Pygal 将其数据输出到世界地图中。在过去的练习中,我们在地图中显示数字,但现在我尝试显示字符串,每个字符串分别称为“高收入”、“低收入”等。到目前为止,我有这个代码:
import csv
import pygal
from pygal.maps.world import World
from country_codes import get_country_code
# Loading data
filename = 'metadata_country.csv'
with open(filename) as f:
children_list = csv.reader(f)
header_row = next(children_list)
incomes = {}
for data in children_list:
try:
country_code = get_country_code(data[4])
child_income = data[2]
except ValueError:
print("Data missing for " + country_code)
else:
incomes[country_code] = child_income
income_levels = ['High income', 'Lower middle income', 'Upper Middle income', 'Low income']
# Filtering the child incomes dictionary
children_high, children_upper_middle, children_lower_middle, children_low = {}, {}, {}, {}
for country, income in incomes.items():
if income == income_levels[0]:
children_high[country] = income
elif income == income_levels[1]:
children_lower_middle[country] = income
elif income == income_levels[2]:
children_upper_middle[country] = income
else:
children_low[country] = income
world_map = World()
world_map.title = 'Children income per country'
world_map.add('High income', children_high)
world_map.add('Upper Middle income', children_upper_middle)
world_map.add('Lower middle income', children_lower_middle)
world_map.add('Low income', children_low)
world_map.render_to_file('children_income.svg')
但我收到以下错误:
File "C:\Users\Matheus\AppData\Roaming\Python\Python38\site-packages\pygal\graph\map.py", line 83, in _plot
ratio = .3 + .7 * (value - min_) / (max_ - min_)
TypeError: unsupported operand type(s) for -: 'str' and 'str'
有人可以帮我解决问题吗?我是 Python 新手,也是 Pygal 新手。只是为了好奇而做。谢谢! Link to the .csv file if needed.
【问题讨论】: