Заполнение нуля для всех пустых временных интервалов для каждого кластера (региона) как часть анализа ответа / отправки скорой помощи - PullRequest
0 голосов
/ 29 января 2020

У меня есть мои данные из агентств скорой помощи. Я создал кластеры для местоположений, от которых они отвечают, и создал временные корзины, чтобы разделить время на управляемые корзины. Затем я сгруппировал данные по кластерам, а затем по бинам, и количество столбцов в каждом кластере на кластер также было сгруппировано. Мне нужно заполнить нули для всех периодов времени, когда в столбце количества инцидентов не было инцидентов. Я пробовал вложенный для l oop с if, чтобы заставить его работать. Он работает слишком медленно, и я пытаюсь найти способ переключиться на понимание вложенного списка с помощью операторов if else.

count_values = ers_bin_groupby['no_of_incidents'].values

vals = ers_unique 

"ers_unique" - это список всех уникальных временных интервалов для каждого кластера

def fill_missing(count_values,vals):
smoothed_regions=[]
ind=0  # ind iterates over count_values only
for p in range(0,posts):
    smoothed_bins=[]
    for i in range(max(minute_bin_create_times)):
        if i in vals[p]:
            smoothed_bins.append(count_values[ind])
            ind+=1
        else:
            smoothed_bins.append(0)
    smoothed_regions.extend(smoothed_bins)
    print(p)
return smoothed_regions

Это моя попытка понять список с помощью оператора if

def fill_missing2(count_values, vals):
   smoothed_regions = []
   ind = 0   #ind iterates over count_values only
   smoothed_regions =[[count_values[ind] ind+=1 if i in vals[p] else 0 
                  for i in range(max(minute_bin_create_times))] 
                  for p in range(0,posts)]

Я не могу понять, нужен ли мне "ind + = 1", чтобы он проходил через count_values ​​

Вот пример групповых данных, с которыми я работаю, есть 20 постов и более 500 000 временных интервалов

 post_area  time_bin    
 0             7      1
               59     1
               104    1
               113    1
               117    1
               147    1
               249    1
               255    1

Это пример списка ers_unique [[7, 59, 104, 113, 117, 147, 249, 255, 277, 283, 292, 310, 312, 358, 393, 406, 480, 537, 550, 553, 622,

1 Ответ

0 голосов
/ 02 февраля 2020

Помимо проблемы ind += 1, обратите внимание, что smoothed_regions.extend(smoothed_bins) означает, что вы возвращаете плоский список, а не список smoothed_bins (как в вашей попытке).

Без примера ввода / вывода Я не могу проверить приведенный ниже код, но надеюсь, что все в порядке.

Сначала замените индексы на итерации:

def fill_missing(count_values,vals):
    smoothed_regions=[]
    count_it = iter(count_values) # iterates over count_values only
    for val in vals: # I assume that posts == len(vals)
        smoothed_bins=[]
        for i in range(max(minute_bin_create_times)):
            if i in val:
                smoothed_bins.append(next(count_it))
            else:
                smoothed_bins.append(0)
        smoothed_regions.extend(smoothed_bins)
    return smoothed_regions

Затем замените деталь if ... append... else... append ... на append(... if ... else ...), то есть: используйте выражение вместо оператора:

def fill_missing(count_values,vals):
    smoothed_regions=[]
    count_it = iter(count_values) # iterates over count_values only
    for val in vals:
        smoothed_bins=[]
        for i in range(max(minute_bin_create_times)):
            smoothed_bins.append(next(count_it) if i in val else 0)
        smoothed_regions.extend(smoothed_bins)
    return smoothed_regions

Теперь вы можете создать первое понимание списка:

def fill_missing(count_values,vals):
    smoothed_regions=[]
    count_it = iter(count_values) # iterates over count_values only
    for val in vals[:posts]: # posts == len(vals)??
        smoothed_bins=[next(count_it) if i in val else 0 
                       for i in range(max(minute_bin_create_times))]
        smoothed_regions.extend(smoothed_bins)
    return smoothed_regions

Затем вам нужно построить список все сглаживать, связывать и выравнивать (extend). На самом деле, генератор кажется (мне) более приспособленным, чем список:

def fill_missing(count_values,vals):
    count_it = iter(count_values) # iterates over count_values only
    all_smoothed_bins = ([next(count_it) if i in val else 0 
                   for i in range(max(minute_bin_create_times))] for val in vals[:posts])
    smoothed_regions = [v for smoothed_bins in all_smoothed_bins for v in smoothed_bins]
    return smoothed_regions

Вы можете вставить последние три строки, если хотите:

def fill_missing(count_values,vals):
    count_it = iter(count_values) # iterates over count_values only
    return [v
        for smoothed_bins in (
                [next(count_it) if i in val else 0 
                 for i in range(max(minute_bin_create_times))]
             for val in vals[:posts]
        )
        for v in smoothed_bins]
...