在Pandas数据框中插入NaN单元非常容易:
In [98]: df
Out[98]:
neg neu pos avg
250 0.508475 0.527027 0.641292 0.558931
500 NaN NaN NaN NaN
1000 0.650000 0.571429 0.653983 0.625137
2000 NaN NaN NaN NaN
3000 0.619718 0.663158 0.665468 0.649448
4000 NaN NaN NaN NaN
6000 NaN NaN NaN NaN
8000 NaN NaN NaN NaN
10000 NaN NaN NaN NaN
20000 NaN NaN NaN NaN
30000 NaN NaN NaN NaN
50000 NaN NaN NaN NaN
[12 rows x 4 columns]
In [99]: df.interpolate(method='nearest', axis=0)
Out[99]:
neg neu pos avg
250 0.508475 0.527027 0.641292 0.558931
500 0.508475 0.527027 0.641292 0.558931
1000 0.650000 0.571429 0.653983 0.625137
2000 0.650000 0.571429 0.653983 0.625137
3000 0.619718 0.663158 0.665468 0.649448
4000 NaN NaN NaN NaN
6000 NaN NaN NaN NaN
8000 NaN NaN NaN NaN
10000 NaN NaN NaN NaN
20000 NaN NaN NaN NaN
30000 NaN NaN NaN NaN
50000 NaN NaN NaN NaN
[12 rows x 4 columns]
我还希望它使用给定的方法外推插值范围之外的NaN值。我怎么才能做到最好?
收益率
注意:我把你的
df
稍微改了一点,以显示使用nearest
插值与使用df.fillna
插值有什么不同。(请参见索引为999的行。)我还添加了一行索引为0的nan,以表明
bfill()
也可能是必要的。推断熊猫
DataFrame
可能是外推的,但是熊猫内部没有简单的方法调用,需要另一个库(例如scipy.optimize)。外推
一般来说,外推需要确定assumptions about the data被外推。一种方法是通过curve fitting一些通用的参数化方程来找到最能描述现有数据的参数值,然后用于计算超出该数据范围的值。这种方法的难点和局限性在于,当选择参数化方程时,必须对趋势进行一些假设。这可以通过使用不同的方程进行反复试验来找到,以给出所需的结果,或者有时可以从数据源中推断出来。该问题中提供的数据实际上不够大,不足以获得一个很好的拟合曲线;但是,它足以说明问题。
下面是用3阶多项式外推
DataFrame
的一个例子此通用函数(
func()
)对每个列进行曲线拟合,以获得唯一的列特定参数(即a,b,c,d)。然后,使用这些参数化方程来外推每个列中具有NaN
s的所有索引的数据外推结果
avg
列的绘图如果没有更大的数据集或不知道数据的来源,这个结果可能是完全错误的,但是应该举例说明推断
DataFrame
的过程。在func()
中假设的方程可能需要用来进行运算,以得到正确的外推。此外,没有试图使代码有效。更新:
如果索引是非数字的,比如
DatetimeIndex
,那么see this answer是如何推断它们的。相关问题 更多 >
编程相关推荐