Pandas 数据帧interpolate()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-interpolate-method

在本教程中,我们将学习 PandasDataFrame.interpolate()方法。此方法使用插值方法填充 NaN 值。带有多索引的数据帧支持method='linear'。当此方法应用于数据帧时,它通过填充空值返回序列或数据帧。如果inplace=True返回无。

下图显示了DataFrame.interpolate()方法的语法。

句法

DataFrame.interpolate(method='linear', axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)

因素

方法: str,默认‘线性’。其他方法有:{线性、时间、索引、值、pad、最近、零、slinear、二次、三次、样条、重心、多项式、krogh、分片 多项式、样条、pchip、akima、立方样条、from 导数}。

轴:“0”代表索引,“1”代表列,默认值为无。它表示沿哪个轴进行插值。

极限:代表 int,可选,但必须大于 0。它指示要填充的最大连续 nan 数。

inplace: 表示 bool(真或假),默认值为 False。

limit_direction: 包括‘向前’、‘向后’、‘两者’可选。它表示要在指定方向上填充的连续空值。

示例:使用DataFrame.interpolate() 方法插值缺失值

使用linear方法,DataFrame.interpolate() 方法通过忽略索引来填充空值,并将这些值视为等距。见下面的例子。

#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
#creating the DataFrame
df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),(np.nan, 2.0, np.nan, np.nan),(2.0, 3.0, np.nan, 9.0),],columns=list('abcd'))
print(df)
print("-----Filling the null values using the linear method-----")
print(df.interpolate(method='linear', limit_direction='forward'))

a b c d 0 0.0 NAn-1.0 1.0 1 NAn 2.0 NAn 2 2.0 3.0 NAn 9.0 -使用线性方法填充空值- a b c d 0 0.0 NAn-1.0 1.0 1 1.0 2.0-1.0 5.0 2 2.0 3.0-1.0 9.0

示例:使用DataFrame.interpolate() 方法和polynomial方法向前插入缺失值。

DataFrame.interpolate() 方法使用polynomial方法填充空值。当我们使用polynomial方法时,我们必须指定样条或多项式的顺序。见下面的例子。

#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
#creating the DataFrame
df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),(np.nan, 2.0, np.nan, np.nan),(2.0, 3.0, np.nan, 9.0),],columns=list('abcd'))
print(df)
print("-----Filling the null values using the polynomial method-----")
print(df['a'].interpolate(method='polynomial', limit_direction='forward',order=1))

a b c d 0 0.0 NAn-1.0 1.0 1 NAn 2.0 NAn 2 2.0 3.0 NAn 9.0 -使用多项式方法填充空值- 0 0.0 1 1.0 2 2.0 名称:a,数据类型:float64

示例:在DataFrame.interpolate() 方法中设置method= pad

我们可以使用pad方法在正向插入缺失值,该方法使用现有值填充 NaNs。见下面的例子。

#importing pandas as pd
import pandas as pd
#importing numpy as np
import numpy as np
#creating the DataFrame
df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),(np.nan, 2.0, np.nan, np.nan),(2.0, 3.0, np.nan, 9.0),],columns=list('abcd'))
print(df)
print("-----Filling the null values using the pad method-----")
print(df.interpolate(method='pad', limit_direction='forward'))

a b c d 0 0.0 NAn-1.0 1.0 1 NAn 2.0 NAn 2 2.0 3.0 NAn 9.0 -使用填充方法填充空值- a b c d 0 0.0 NAn-1.0 1.0 1 0.0 2.0-1.0 1.0 2 2.0 3.0-1.0 9.0

结论:

在本教程中,我们学习了 PandasDataFrame.interpolate()方法。我们学习了语法、参数,并通过在数据帧上应用这种方法,我们解决了示例并理解了DataFrame.interpolate()方法。