我正在尝试根据不同列中的数字位置插入值。以本专栏为例:
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 中完成。
最佳答案
欢迎来到堆栈溢出。
我们需要为此创建一个自定义函数,除非有一个我不知道的标准库函数,这是完全可能的。我将创建一个函数,允许您按价格输入债券,并将其插入具有适当优惠券的数据框中。
假设我们从一个排序的数据帧开始。
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
使用数据帧中的价格计算新债券息票的函数。
# 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
如果这个答案符合您的需求,请记得选择正确答案。谢谢。
关于python - 在数据帧的两列之间进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56994542/