在 Dataframe 的两列之间进行插值

Interpolate between two columns of a Dataframe

我正在尝试根据数字在不同列中的位置插入一个值。以本栏目为例:

Coupon  Price
9.5     109.04
9.375   108.79
9.25    108.54
9.125   108.29
9       108.04
8.875   107.79
8.75    107.54
8.625   107.29
8.5     107.04
8.375   106.79
8.25    106.54

假设我有一个像 107 这样的数字。我希望能够找到 107 与 107.04 和 106.79 的相对距离,以插入在 8.5 和 8.375 之间具有相同相对距离的值,优惠券价值相同指数。这可能吗?我可以使用 FORECAST 方法在 excel 中解决这个问题,但想知道它是否可以在 Python 中完成。

可能有一个函数可以在某个地方为您完成工作,但我的建议是您自己对其进行编程,这一点都不难,而且是一个很好的编程练习。只需找到该段的斜率并使用直线方程:

(y-y0) = ((y1-y0)/(x1-x0))*(x-x0) -> y = ((y1-y0)/(x1-x0))*(x-x0) + y0

Where:

x -> Your given value (107)
x1 & x0 -> The values right above and below (107.04 & 106.79)
y1 & y0 -> The corresponding values to x1 & x0 (8.5 & 8.375)
y -> Your target value.

只是基础 high-school 数学 ;-)

欢迎来到 Stack Overflow。

我们需要为此创建一个自定义函数,除非有一个我不知道的标准库函数,这是完全可能的。我将创建一个允许您按价格输入债券的函数,它将与适当的优惠券一起插入到数据框中。

假设我们从一个排序的数据框开始。

print(df)

    Coupon   Price
0    9.500  109.04
1    9.375  108.79
2    9.250  108.54
3    9.125  108.29
4    9.000  108.04
5    8.875  107.79
6    8.750  107.54
7    8.625  107.29
8    8.500  107.04
9    8.375  106.79
10   8.250  106.54

我已经在函数中插入了注释。

def add_bond(Price, df):
    # Add row
    df.loc[df.shape[0]] = [np.NaN, Price]
    df = df.sort_values('Price', ascending=False).reset_index(drop=True)

    # Get index
    idx = df[df['Price'] == Price].head(1).index.tolist()[0]

    # Get the distance from Prices from previous row to next row
    span = abs(df.iloc[idx-1, 1] - df.iloc[idx +1, 1]).round(4)

    # Get the distance and direction from Price from previous row to new value
    terp = (df.iloc[idx, 1] - df.iloc[idx-1, 1]).round(4)

    # Find the percentage movement from previous in percentage.
    moved = terp / span

    # Finally calculate the move from the previous for Coupon.
    df.iloc[idx, 0] = df.iloc[idx-1,0] + (abs(df.iloc[idx-1,0] - df.iloc[idx+1, 0]) * (moved))

    return df

使用 DataFrame 中的价格计算新债券息票的函数。

# Add 107
df =  add_bond(107, df)
print(df)

    Coupon   Price
0    9.500  109.04
1    9.375  108.79
2    9.250  108.54
3    9.125  108.29
4    9.000  108.04
5    8.875  107.79
6    8.750  107.54
7    8.625  107.29
8    8.500  107.04
9    8.480  107.00
10   8.375  106.79
11   8.250  106.54

再添加一个。

# Add 107.9
df = add_bond(107.9, df)
print(df)

    Coupon   Price
0    9.500  109.04
1    9.375  108.79
2    9.250  108.54
3    9.125  108.29
4    9.000  108.04
5    8.930  107.90
6    8.875  107.79
7    8.750  107.54
8    8.625  107.29
9    8.500  107.04
10   8.480  107.00
11   8.375  106.79
12   8.250  106.54

如果这个答案符合您的需要,请记得select更正答案。谢谢。