[英]How to linearly interpolate pandas columns values, based on a particular column
我有一個 pandas dataframe 之類的
A B C D
0 1.0 0.50 1.25 1.25
1 1.5 1.30 1.10 1.25
2 2.0 0.40 1.25 1.25
3 2.5 1.50 1.35 1.25
4 3.0 1.70 1.20 1.25
5 3.5 0.90 0.60 0.63
是否有一個內置的 pandas function 在這種情況下可以幫助我在任何列中插入值[B,C,D]
基於列'A'
值。
例如,當輸入為2.25
時,我需要導出 Column 'B'
的線性插值。 ( 'A'
列值將用作參考)。 所以這里我的預期答案是從列'B'
[0.4, 1.50]
之間的插值。 即0.95
我寫了一個專門的 function 來獲取(x1,y1) & (x2,y2)
值,然后使用兩個斜率/截距公式來得到答案(但我覺得這是一個矯枉過正,我錯過了一些簡單的 function pandas 庫)。
您可以使用pandas
中的interpolate
功能:
# set `A` as index for interpolation
df = df.set_index('A')
# insert the new value
x = 2.25
new_idx = sorted(list(df.index) +[x])
df.reindex(new_idx).interpolate('index').loc[x]
Output:
B 0.95
C 1.30
D 1.25
Name: 2.25, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.