这是我的数据:
Year Country Albania Andorra Armenia Austria Azerbaijan
2009 Lithuania 0 0 0 0 1
2009 Israel 0 7 0 0 0
2008 Israel 1 2 2 0 4
2008 Lithuania 1 5 1 0 8
实际上,它是csv文件,分隔符是,所以原始数据是:
^{pr2}$其中,列表的第一个元素表示立陶宛按列汇总,第二个元素表示以色列按列汇总(阿尔巴尼亚列)?在
我是python的初学者,不太懂python的技巧。我知道的是我的代码可能太复杂了。在
我想得到这个:
final_dict = {Albania: [1, 1], Andorra: [5, 9], Armenia: [1, 2], Austria: [0, 0], Azerbaijan: [9, 4]}
产出说明:对于第一排的每个国家(阿尔巴尼亚、安道尔、亚美尼亚、奥地利和阿塞拜疆),我想从国家一栏中按国家列出总和。在
Andorra: [5,9]
# 5 is sum for Lithuania in Andorra column
# 9 is sum for Israel in Andorra column
您的帽子戏法正在使用the defaultdict from the collections module,请搜索
所以,你会发现很多有用的例子,下面是我的答案
数据的示例输出是
^{pr2}$编辑
如果您反对}对未初始化的情况下返回可选的默认值
defaultdict
,那么可以使用普通dict
的.get
方法,该方法允许您在{如您所见,它有点笨拙,但仍然可以管理。在
您可以使用the Pandas module,它非常适合这种类型的应用程序:
要查询每个列的结果,只需执行以下操作:
^{pr2}$好的,那么您希望这些行按年份汇总:
我有权把它输出到另一个csv文件中。数据结构非常容易出错,因为它取决于列的顺序。最好在dict中使用中间dict来为聚合指定名称->;请参阅@gboffi对您的问题的评论。在
相关问题 更多 >
编程相关推荐