简体   繁体   中英

How to find the first occurrance of sum of closest value to the given value

Have got an array like below with columns ['item','Space','rem_spc']

array([['Pineapple', 0.5, 0.5],
       ['Mango', 0.75, 0.25],
       ['Apple', 0.375, 0.625],
       ['Melons', 0.25, 0.75],
       ['Grape', 0.125, 0.875]], dtype=object)

need to convert this array to dataframe along with new column ['nxt_item'] which should be generated for first array row alone(Here, for Pineapple) with below conditions:

  1. to find the first nearest items array['Space'] whose sum equals array['rem_spc'] for pineapple.

Expected Output:

item        Space   rem_spc     nxt_item
Pineapple   0.5     0.5         {Apple, Grape}      #0.5 = 0.375 + 0.125
Mango       0.75    0.25
Apple       0.375   0.625
Melons      0.25    0.75
Grape       0.125   0.875

Thanks!

A possible solution (another would be using binary linear programming):

from itertools import product

n = len(df) - 1
combinations = product([0, 1], repeat=n)
a = np.array(list(combinations))
df['nxt_item'] = np.nan
df.loc[0, 'nxt_item'] = (
    '{' + 
    ', '.join(list(
        df.loc[[False] + 
               a[np.argmin(np.abs(df.iloc[0, 2] - 
                                  np.sum(a * df['Space'][1:].values, axis=1))), :]
               .astype(bool).tolist(), 'item']))
    + '}')

Output:

        item  Space rem_spc        nxt_item
0  Pineapple    0.5     0.5  {Apple, Grape}
1      Mango   0.75    0.25             NaN
2      Apple  0.375   0.625             NaN
3     Melons   0.25    0.75             NaN
4      Grape  0.125   0.875             NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM