我有一份数据清单,上面有姓名、年份、金额和结果。我想计算一下每年的总赢额和总输额。(初学者最好使用列表函数)谢谢
我试过使用dictionary,但它似乎增加了很多复杂性,而且一直显示出错误。你知道吗
>>> my_list = [ ['a', '2013', '10.22', 'won'], ['b', '2012', '11.23', 'won'], ['c', '2013', '12.62', 'lost']]
>>> headers = ['name', 'year', 'amount', 'result']
>>> my_dict = {k: [x [i] for x in my_list] for i, k in enumerate(headers)}
我希望回报的形式是
Year Total Won Total Lost
2012 11.23 0
2013 10.22 12.62
假设您2012年的预期产出是一个输入错误(您的数据集显示11.23为总赢款),您可以使用
itertools.groupby
和sum
按年度汇总总赢款/输款。您可以根据需要修改输出格式,但这应该可以让您继续。你知道吗如果您对使用pandas感到足够舒服,您可以在数据上包装一个pivot table。我假设结果表就是您想要显示的。你知道吗
将
NaN
更改为0
从那里你可以有乐趣,做一些更好的事情,如计算净变化。你知道吗
我建议写一些代码,而不是字典理解(你的方法)。此解决方案符合您的要求。你知道吗
这张照片:
相关问题 更多 >
编程相关推荐