填充 pandas dataframe 中的缺失值
有时,我们可能有一个缺失值的数据集。有很多方法可以使用某些方法来替换丢失的数据。
ffill()
(前向填充)是替换 dataframe 中缺失值的方法之一。此方法将 nan 替换为先前的行或列值。
pandas 中 ffill()
方法的语法
# python 3.x
dataframe.ffill(axis, inplace, limit, downcast)
ffill()
方法采用四个可选参数:
axis
指定从何处填充缺失值。值 0 表示行,1 表示列。inplace
可以是 true 或 false。true 指定在当前 dataframe 中进行更改,而 false 表示创建具有填充值的新 dataframe 的单独副本。limit
指定要沿轴连续填充的最大缺失值数。downcast
指定要为特定数据类型填充的值字典。
使用 pandas 中的 ffill()
方法填充 dataframe 中的缺失值
沿行轴填充缺失值
在下面的代码中,我们有一个缺失值用 none 或 nan 表示的 dataframe。我们已经显示了实际的 dataframe,然后将 ffill()
方法应用于该 dataframe。
默认情况下,ffill()
方法会沿着行/索引轴替换缺失值。nan 将替换为该单元格上一行的值。
第一行在输出中仍然包含 nan,因为没有前一行。
示例代码:
# python 3.x
import pandas as pd
df = pd.dataframe(
{
"c1": [2, 7, none, 4],
"c2": [none, 2, none, 3],
"c3": [2, none, 6, 5],
"c4": [5, 2, 8, none],
}
)
display(df)
df2 = df.ffill()
display(df2)
输出:
沿列轴填充缺失值
在这里,我们将指定 axis=1
。它将通过观察相应单元格的前一列中的值来填充缺失值。
在输出中,除了两个值之外,所有值都被填充。因为我们没有列 1
的前一列,所以该值仍然是 nan。
第 2 列中的值是 nan,因为前一列中对应的单元格也是 nan。
示例代码:
# python 3.x
import pandas as pd
df = pd.dataframe(
{
"c1": [2, 7, none, 4],
"c2": [none, 2, none, 3],
"c3": [2, none, 6, 5],
"c4": [5, 2, 8, none],
}
)
display(df)
df2 = df.ffill(axis=1)
display(df2)
输出:
使用 limit
限制要填充的连续 nan 的数量
我们可以使用 limit
参数来限制沿行或列轴填充的连续缺失值的数量。
在下面的代码中,我们有实际的 dataframe,其中最后三行有连续的 nan。如果我们指定 limit=2
,则不能超过两个连续的 nan 可以沿行轴填充。
这就是为什么最后一行中的 nan 仍未填充的原因。
示例代码:
# python 3.x
import pandas as pd
df = pd.dataframe(
{
"c1": [2, 7, none, 4],
"c2": [4, none, none, none],
"c3": [6, 6, 6, 5],
"c4": [none, 2, 8, none],
}
)
display(df)
df2 = df.ffill(axis=0, limit=2)
display(df2)
输出:
使用 inplace
填充原始 dataframe 中的值
假设我们想要在原始 dataframe 中进行更改,而不是在另一个 dataframe 中复制具有填充值的 dataframe。在这种情况下,我们可以使用值为 true 的 inplace
参数。
示例代码:
# python 3.x
import pandas as pd
df = pd.dataframe(
{
"c1": [2, 7, none, 4],
"c2": [4, none, none, none],
"c3": [6, 6, 6, 5],
"c4": [none, 2, 8, none],
}
)
display(df)
df.ffill(inplace=true)
display(df)
输出:
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串