Python: returning the average between two values in a dictionary -


i have function:

def find_nearest(array,value):     idx = (np.abs(array-value)).argmin()     return array[idx]  def df_to_count_dict(df):      count_dict = counter(df.values)     holder = []     in range(1,max(list(count_dict.keys()))):             if in count_dict.keys(): continue             holder.append(i)         in holder:         j = find_nearest(np.array(list(count_dict.keys())),i)         count_dict.update({i:count_dict[j]})      return count_dict 

what takes data series , uses counter function collection return dictionary. replaces values not in dictionary closest value.

now, want amend function return same object, count_dict replace values not in keys of dictionary average between missing value between.

this best explained example:

take

test = pd.series([1,2,3,3,7,7,7,8]) 

without function above get:

counter(test.values) out[459]: counter({1: 1, 2: 1, 3: 2, 7: 3, 8: 1}) 

using function get

df_to_count_dict(test) out[458]: counter({1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 2, 7: 3, 8: 1}) 

as can see has added keys 4,5,6 values 2 2 value of closest key (the closest key 3).

what have return average between value of lower closest key , upper closest key, upper closest key 3, has value 2, , upper closest key 7, has value 3, want final product like:

df_to_count_dict(test) out[458]: counter({1: 1, 2: 1, 3: 2, 4: 2.5, 5: 2.5, 6: 2.5, 7: 3, 8: 1}) 

i hope can help

this lot school work. should figure out self. here hint. query being asked develop finding mean between predecessor's count , successor's count. predessor largest key smaller or equal input , successor smallest key larger input.

if need o(log(n))-complexity might @ binary search trees bintrees package https://pypi.python.org/pypi/bintrees/2.0.4.


Comments

Popular posts from this blog

android - ConstraintLayout: Realign baseline constraint in case if dependent view visibility was set to GONE -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -

c# - Update a combobox from a presenter (MVP) -