如何按嵌套列表的第一个元素对嵌套列表进行分组?

2024-09-29 07:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份数据清单,上面有姓名、年份、金额和结果。我想计算一下每年的总赢额和总输额。(初学者最好使用列表函数)谢谢

我试过使用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

Tags: 数据in列表formy金额listheaders
3条回答

假设您2012年的预期产出是一个输入错误(您的数据集显示11.23为总赢款),您可以使用itertools.groupbysum按年度汇总总赢款/输款。您可以根据需要修改输出格式,但这应该可以让您继续。你知道吗

from itertools import groupby
from operator import itemgetter

results = [['a', '2013', '10.22', 'won'], ['b', '2012', '11.23', 'won'], ['c', '2013', '12.62', 'lost']]
for year, values in groupby(sorted(results, key=itemgetter(1)), key=itemgetter(1)):
    values = list(values)
    won = sum(float(v[2]) for v in values if v[3] == 'won')
    lost = sum(float(v[2]) for v in values if v[3] == 'lost')
    print(f'Year: {year} Total Won: {won} Total Lost: {lost}')

# Year: 2012 Total Won: 11.23 Total Lost: 0
# Year: 2013 Total Won: 10.22 Total Lost: 12.62

如果您对使用pandas感到足够舒服,您可以在数据上包装一个pivot table。我假设结果表就是您想要显示的。你知道吗

import pandas as pd

headers = ['name', 'year', 'amount', 'result']
my_list = [ ['a', '2013', '10.22', 'won'],
            ['b', '2012', '11.23', 'won'], 
            ['c', '2013', '12.62', 'lost']]

df = pd.DataFrame(my_list, columns=headers)
df.amount = pd.to_numeric(df.amount) # makes amount numeric

df2 = pd.pivot_table(df, index='year', columns='result', values='amount', aggfunc=sum)
# result   lost    won
# year                
# 2012      NaN  11.23
# 2013    12.62  10.22

NaN更改为0

df2.fillna(0, inplace=True)

从那里你可以有乐趣,做一些更好的事情,如计算净变化。你知道吗

df2['net'] = df2.won - df2.lost
# result   lost    won    net
# year                       
# 2012     0.00  11.23  11.23
# 2013    12.62  10.22  -2.40

我建议写一些代码,而不是字典理解(你的方法)。此解决方案符合您的要求。你知道吗

from collections import defaultdict
d = defaultdict(dict)

my_list = [ ['a', '2013', '10.22', 'won'], ['b', '2012', '11.23', 'won'], ['c', '2013', '12.62', 'lost']]

for rec in my_list:
    if rec[3] in d[rec[1]]:
        d[rec[1]][rec[3]] += float(rec[2])
    else:
        d[rec[1]][rec[3]] = float(rec[2])

print('Year', "won", "    lost")
for year in sorted(d):
    print(year, '\t'.join([str(d[year].get('won', '0')), \
                           str(d[year].get('lost', '0'))]))

这张照片:

Year won     lost
2012 11.23  0
2013 10.22  12.62

相关问题 更多 >