我有一个看起来像这样的数据框df
print(df)
x outlier_flag
10 1
NaN 1
30 1
543 -1
50 1
我想用 row['A][i-1]
和 row 之间的插值替换标记为
,表示我想用 40 替换显示的错误值 543。outlier_flag==-1
的值['A][i+1]
我能做的是
df['x'] = df.apply(lambda row: np.nan if row['outlier_flag']==-1 else row['x'], axis=1)
df.interpolate(method='polynomial', order=3, inplace=True)
但我不想这样做,因为这还会插入 df['x']
中未用 outlier_flag 标记的
(参见第二行)!纯 nan
值=-1nan
值,未由标志标记,我想在以后的任务中保留为 nan
。
那么,有没有办法就地进行插值,即使对于像 543
这样不是 nan
的值也是如此?
我尝试过这样做
df['x'] = df.apply(lambda row: row['x'].interpolate(method='polynomial', order=3) if row['outlier_flag']==-1 else row['x'], axis=1)
但这会引发错误,因为只能插值nan
,而543
是int
。你有什么建议给我吗? TNx
最佳答案
这是您可以使用 interpolate()
的一种方式如您所愿。
您可以首先创建一个列表,其中包含离群值标志为 -1 的行的索引,然后使用 loc
将 x 中的值替换为 np.nan
:
incl = df.index[df['outlier_flag'] == -1].tolist()
df.loc[df.index.isin(incl), 'x'] = np.nan
>>> df
x outlier_flag
0 10.0 1
1 NaN 1
2 30.0 1
3 NaN -1
4 50.0 1
然后,您可以使用 np.where
来检查 x isnull()
以及该特定索引是否在您创建的列表中,并应用插值:
df['x']= np.where( (df['x'].isnull()) & (df.index.isin(incl)), df['x'].interpolate(),df['x'])
打印内容:
x outlier_flag
0 10.0 1
1 NaN 1
2 30.0 1
3 40.0 -1
4 50.0 1
关于python - 如何用插值替换 pandas df 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69194611/