Итого по двум условиям в списке списков - PullRequest
0 голосов
/ 12 июня 2019
    cust_id = semi_final_df['0_x'].tolist()
    date = semi_final_df[1].tolist()
    total_amount = semi_final_df[0].tolist()
    prod_num = semi_final_df['0_y'].tolist()

    prod_deduped = []
    quant_cleaned = []
    product_net_amount = []
    cust_id_final = []
    date_final = []
    for row in total_amount:
        quant_cleaned.append(float(row))  

    for unique_prodz in prod_num:
        if unique_prodz not in prod_deduped:
            prod_deduped.append(unique_prodz)

    for unique_product in prod_deduped:
        indices = [i for i, x in enumerate(prod_num) if x == unique_product]
        product_total = 0
        for index in indices:
            product_total += quant_cleaned[index]
        product_net_amount.append(product_total)
        first_index = prod_num.index(unique_product)
        cust_id_final.append(cust_id[first_index])
        date_final.append(date[first_index])

Выше кода вычисляет сумму суммы одним условием для суммирования суммы по счету.Данные имели несколько строк, но имели один и тот же номер счета / продукта.

Проблема: мне нужно изменить приведенный ниже код, чтобы можно было суммировать по уникальному продукту и уникальной дате.

Я попробовал, но получаю ошибку значения -

, сказав, что x, y отсутствует в списке

Согласно моемупонимание проблемы заключается в том, что я объединяю два дедуплицированных списка разной длины, а затем пытаюсь перебрать встроенный результат.

Эта строка вызывает ошибку

для i, [x, y] в перечислении (zipped_list):

Любая помощь будет искренне оценена.Вот вторая партия кода с комментариями.

    from itertools import zip_longest

    #I have not included the code for the three lists below but you can assume they are populated as these are the lists that I will be #working off of. They are of the same length.
    prod_numbers = []
    datesz = []
    converted_quant = []
    #Code to dedupe date and product which will end up being different lengths. These two lists are populated by the two for loops below
    prod_deduped = []
    dates_deduped = []

    for unique_prodz in prod_numbers:
        if unique_prodz not in prod_deduped:
            prod_deduped.append(unique_prodz)

    for unique_date in datesz:
        if unique_date not in dates_deduped:
            dates_deduped.append(unique_date)


    #Now for the fun part. Time to sum by date and product. The three lists below are empty until we run the code
    converted_net_amount = []
    prod_id_final = []
    date_final = []

    #I zipped the list together using itertools which I imported at the top
    for unique_product, unique_date in zip_longest(prod_deduped, dates_deduped, fillvalue = ''):
        indices = []
        zipped_object = zip(prod_numbers, datesz)
        zipped_list = list(zipped_object)
        for i,[x, y] in enumerate(zipped_list):
            if x == unique_product and y == unique_date:
                indices.append(i)
        converted_total = 0
        for index in indices:
            converted_total += converted_quant[index]
        converted_net_amount.append[converted_total]
        first_index = zipped_list.index([unique_product, unique_date])
        prod_id_final.append(prod_numbers[first_index])
        date_final.append(datesz[first_index])

1 Ответ

0 голосов
/ 12 июня 2019
from collections import defaultdict
summed_dictionary = defaultdict(int)
for x, y, z in list:
    summed_dictionary[(x,y)] += z

Использование defaultdict должно решить вашу проблему и намного проще для глаз, чем весь ваш код выше.Я видел это на Reddit этим утром и полагал, что вы пересекались.Кредит парню из reddit на / r / learnpython

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...