New interpolated column from existing table of columns and search queries

I am trying to convert a column to a dataframe to get a new column, with each row in the new column being interpolated from the old column and the lookup table. Example:

Source data frame:

Date       StartingValue
2010-01-01            10
2010-01-02            25
2010-01-03            15
2010-01-04            20

View frame information frame:

StartingValue  NewValue
           10       500
           20      1200
           30      2750

Desired Result:

Date       StartingValue  NewValue
2010-01-01            10       500
2010-01-02            25      1975
2010-01-03            15       850
2010-01-04            20      1200

The index will remain unchanged, and the interpolation should be linear between the nearest rows in the lookup table.

I looked maybe at map()or apply(), but I can't figure out how to use them here, especially with interpolation. All help is appreciated.

+4
source share
2 answers

numpy.interp has this function:

import numpy as np

df['NewValue'] = np.interp(df['StartingValue'].values,
                           lookup_table['StartingValue'].values,
                           lookup_table['NewValue'].values)
+5
source

numpy , pandas:

vals = lookup['StartingValue']
df.merge(lookup.set_index('StartingValue').reindex( \
  range(vals.min(), vals.max()+1, 5)).interpolate().reset_index(), \
  on='StartingValue')
#          Date  StartingValue  NewValue
# 0  2010-01-01             10     500.0
# 1  2010-01-02             25    1975.0
# 2  2010-01-03             15     850.0
# 3  2010-01-04             20    1200.0
+2

Source: https://habr.com/ru/post/1692724/


All Articles