met*_*oia 12 python interpolation pandas
考虑以下示例,其中我们设置示例数据集,创建MultiIndex,取消堆叠数据帧,然后执行线性插值,我们逐行填充:
import pandas as pd # version 0.14.1
import numpy as np # version 1.8.1
df = pd.DataFrame({'location': ['a', 'b'] * 5,
'trees': ['oaks', 'maples'] * 5,
'year': range(2000, 2005) * 2,
'value': [np.NaN, 1, np.NaN, 3, 2, np.NaN, 5, np.NaN, np.NaN, np.NaN]})
df.set_index(['trees', 'location', 'year'], inplace=True)
df = df.unstack()
df = df.interpolate(method='linear', axis=1)
Run Code Online (Sandbox Code Playgroud)
未堆叠数据集的位置如下所示:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 NaN 3 NaN
oaks a NaN 5 NaN NaN 2
Run Code Online (Sandbox Code Playgroud)
作为插值方法,我期望输出:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 NaN
oaks a NaN 5 4 3 2
Run Code Online (Sandbox Code Playgroud)
但相反,该方法产生(注意外推值):
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 3
oaks a NaN 5 4 3 2
Run Code Online (Sandbox Code Playgroud)
有没有办法指示大熊猫不要推断出系列中最后一个非缺失值?
编辑:
我仍然喜欢在熊猫中看到这个功能,但是现在我已经将它实现为numpy中的一个函数,然后我df.apply()用来修改它df.这是的功能left和right参数np.interp(),我是错过了在大熊猫.
def interpolate(a, dec=None):
"""
:param a: a 1d array to be interpolated
:param dec: the number of decimal places with which each
value should be returned
:return: returns an array of integers or floats
"""
# default value is the largest number of decimal places in the input array
if dec is None:
dec = max_decimal(a)
# detect array format convert to numpy as necessary
if type(a) == list:
t = 'list'
b = np.asarray(a, dtype='float')
if type(a) in [pd.Series, np.ndarray]:
b = a
# return the row if it's all nan's
if np.all(np.isnan(b)):
return a
# interpolate
x = np.arange(b.size)
xp = np.where(~np.isnan(b))[0]
fp = b[xp]
interp = np.around(np.interp(x, xp, fp, np.nan, np.nan), decimals=dec)
# return with proper numerical type formatting
# check to make sure there aren't nan's before converting to int
if dec == 0 and np.isnan(np.sum(interp)) == False:
interp = interp.astype(int)
if t == 'list':
return interp.tolist()
else:
return interp
# two little helper functions
def count_decimal(i):
try:
return int(decimal.Decimal(str(i)).as_tuple().exponent) * -1
except ValueError:
return 0
def max_decimal(a):
m = 0
for i in a:
n = count_decimal(i)
if n > m:
m = n
return m
Run Code Online (Sandbox Code Playgroud)
像示例数据集上的魅力一样工作:
In[1]: df.apply(interpolate, axis=1)
Out[1]:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 NaN
oaks a NaN 5 4 3 2
Run Code Online (Sandbox Code Playgroud)
替换以下行:
df = df.interpolate(method='linear', axis=1)
Run Code Online (Sandbox Code Playgroud)
有了这个:
df = df.interpolate(axis=1).where(df.bfill(axis=1).notnull())
Run Code Online (Sandbox Code Playgroud)
它通过使用回填找到尾随NaN的掩码.它不是非常有效,因为它执行两次NaN填充操作,但这些问题通常可能不是问题.
这确实是一个令人费解的功能。这是一个更紧凑的解决方案,可以在初始插值后应用。
def de_extrapolate(row):
extrap = row[row==row[-1]]
if extrap.size > 1:
first_index = extrap.index[1]
row[first_index:] = np.nan
return row
Run Code Online (Sandbox Code Playgroud)
和以前一样,我们有:
In [1]: df.interpolate(axis=1).apply(de_extrapolate, axis=1)
Out[1]:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 NaN
oaks a NaN 5 4 3 2
Run Code Online (Sandbox Code Playgroud)