考虑以下示例,其中我们设置样本数据集,创建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)
未堆叠的数据集如下所示:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 NaN 3 NaN
oaks a NaN 5 NaN NaN 2
作为插值方法,我期待输出:
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 NaN
oaks a NaN 5 4 3 2
但是该方法产生(注意外推值):
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1 2 3 3
oaks a NaN 5 4 3 2
有没有办法指示大熊猫不会推断出系列中最后一个非缺失值?
编辑:
我仍然希望在熊猫中看到这个功能,但是现在我已经将它实现为numpy中的函数,然后我使用df.apply()
来修改df
。这是np.interp()
中left
和right
参数的功能,我在熊猫中错过了这些参数。
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
就像示例数据集上的魅力一样:
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
答案 0 :(得分:6)
替换以下行:
df = df.interpolate(method='linear', axis=1)
用这个:
df = df.interpolate(axis=1).where(df.bfill(axis=1).notnull())
使用回填找到尾随NaN的掩码。它不是非常有效,因为它执行两次NaN填充操作,但这些问题通常可能不是问题。
答案 1 :(得分:0)
这确实是令人费解的功能。这是一个更紧凑的解决方案,可以在初始插值后应用。
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
和以前一样,我们有:
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
答案 2 :(得分:0)
从Pandas版本0.21.0开始,limit_area='inside' tells
df.interpolate`只能填充有效值包围的NaN:
import pandas as pd # version 0.21.0
import numpy as np
df = pd.DataFrame({'location': ['a', 'b'] * 5,
'trees': ['oaks', 'maples'] * 5,
'year': list(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()
df2 = df.interpolate(method='linear', axis=1, limit_area='inside')
print(df2)
收益
value
year 2000 2001 2002 2003 2004
trees location
maples b NaN 1.0 2.0 3.0 NaN
oaks a NaN 5.0 4.0 3.0 2.0