在熊猫栏中向两个方向填充NaN

时间:2015-12-15 02:26:51

标签: python pandas

在pandas.fillna中,

method : {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None
Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap

如何向后和向前填充值?没有一个选项可以做到这一点

3 个答案:

答案 0 :(得分:5)

看起来非常简单,可能会有更快捷的方式,但只需链接两者,就像这样

df.fillna(method='ffill').fillna(method='bfill')

这将首先向前填补,然后向后填补。

答案 1 :(得分:0)

可能适合您的另一个选项是.interpolate方法,例如:

df.interpolate(method='nearest')

取最近的值,有效地向后和向前填充。

答案 2 :(得分:0)

这取决于您要寻找的精确结果以及数据帧中的NaN。在以下情况下,您将看到仅使用两个成功的fillna调用实际上将用值填充数据帧。 interpolate函数均不足。

# Modules #
import pandas
from six import StringIO

# Define #
df = """ C   | Y   | S
         AA  | 10  | NaN
         AA  | 11  | NaN
         AA  | 12  | 52
         AA  | 13  | 53
         AA  | 14  | 54
         AA  | 15  | NaN
         AA  | 16  | NaN"""
df = StringIO(df.replace(' ',''))
df = pandas.read_csv(df, sep="|", header=0)

# Show #
print(df)
print('------------')

# This doesn't work (no propagation) #
df['S'] = df['S'].interpolate(method='nearest')
print(df)
print('------------')

# This work partially (propagation forward only) #
df['S'] = df['S'].interpolate(method='pad')
print(df)
print('------------')

# This works (propagation in both directions) #
df['S'] = df['S'].fillna(method='ffill').fillna(method='bfill')
print(df)
print('------------')
相关问题