python - Pandas 根据上面的行向下填充缺失值

标签 python pandas

我有一个如下所示的数据框:

import pandas as pd
data={'col1':[1,3,3,1,2,3,2,2, 1], 'col2':[np.nan, 1, np.nan, 1, np.nan, np.nan, np.nan, 2, np.nan]}
df=pd.DataFrame(data,columns=['col1', 'col2'])
print df

   col1  col2
0     1   NaN
1     3   1.0
2     3   NaN
3     1   1.0
4     2   NaN
5     3   NaN
6     2   NaN
7     2   2.0
8     1   NaN

如果 col2 的值等于 1.0col2 中的上一行是 1.0。最终的数据框如下所示:

 col1  col2  col3
0     1   NaN   NaN
1     3   1.0   1.0
2     3   NaN   1.0
3     1   1.0   1.0
4     2   NaN   1.0
5     3   NaN   1.0
6     2   NaN   1.0
7     2   2.0   2.0
8     1   NaN   NaN

我尝试的第一种方法是:

df['col3'] = ((df['col2']== 1) | ((df['col2'].shift()== 1))).astype('int' )

这给我留下了这个数据框:

col1  col2  col3
0     1   NaN     0
1     3   1.0     1
2     3   NaN     1
3     1   1.0     1
4     2   NaN     1
5     3   NaN     0
6     2   NaN     0
7     2   2.0     0
8     1   NaN     0

它纠正了缺失值的第一个实例,但不会继续填充缺失值。我还尝试使用 np.where() 函数,我得到了相同的结果。

有没有一种方法可以在 pandas 中写这个,它可以连续修复多个实例?

最佳答案

您可以使用 np.where通过查看 forward-fill 等于 1 的位置,在为 True 的位置填充 1,并在为 False 时回退到 'col2' 的值:

df['col2'] = np.where(df['col2'].ffill() == 1, 1, df['col2'])

结果输出:

   col1  col2
0     1   NaN
1     3   1.0
2     3   1.0
3     1   1.0
4     2   1.0
5     3   1.0
6     2   1.0
7     2   2.0
8     1   NaN

关于python - Pandas 根据上面的行向下填充缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447598/

相关文章:

python-3.x - 用于大写列的 lambda 代码不起作用

python - Pandas ,分组并在组中找到最大值,返回值和计数

python - 如何配置 vscode 以发现 python 单元测试

python - 我有一个单词的 df,我想知道它们是否在英语词典中

python - 从 shapely.geometry.polygon 导入多边形时出错

python - 一个包含 6 个元素的列表中的 3 个数字如何求和?

python / Pandas : Use lookup DataFrame + function to replace specific/null values in DataFrame

python-3.x - Pandas 基于 groupby 创建百分位字段,级别为 1

python - Sqlite3 Db 转 Json,用于 Highcharts?

python - Python 中的 10,000 多个点 3D 散点图(带快速渲染)