考虑以下 pandas 数据框
reference sicovam label id date TTM price
0 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 18 52.69
1 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 30 NaN
2 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 49 53.11
3 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 60 NaN
4 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 77 53.69
5 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 90 NaN
6 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 109 54.42
7 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 137 55.15
8 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 171 55.80
9 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 180 NaN
10 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 15 50.04
11 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 30 NaN
12 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 46 50.52
13 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 60 NaN
14 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 74 51.17
15 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 90 NaN
16 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 106 51.95
17 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 134 52.73
18 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 168 53.46
19 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-05 180 NaN
reference
按sicovam
、、label
和列分组后,我想通过对值进行线性插值来填充列id
的值,即在线性插值公式中,是并且是变量。date
NaN
price
TTM
price
y
TTM
x
到目前为止,我已构建了以下线路。
def intepolate_group(group):
group["price"] = group["price"].interpolate(method='linear', limit_direction='both', axis=0)
return group
new_df = df.groupby(["reference","sicovam","label","id","date"])[["TTM","price"]].apply(intepolate_group)
尽管如此,我得到的结果是对每个组的索引号进行线性插值。例如,对于数据集的以下部分,我得到的54.06
是 而不是53.99
。我还需要什么才能对 TTM 变量进行插值?
PS:我想避免通过循环(而不是分组)进行屏蔽并将其设置TTM
为索引,因为数据框非常大,这种情况需要花费相当多的时间。
4 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 77 53.69
5 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 90 NaN
6 SCOM_WTI 68801903 WTI Nymex BBG:CL 2015-01-02 109 54.42
以下是一种方法:
输出:
解释
df.set_index
并应用df.groupby
。groupby.transform
并pd.Series.interpolate
一起使用method='index'
。Series.values
通过链式分配将结果重新赋值给df['price']
。