问题描述
假设我有一个带有某些 NaN
s的DataFrame:
Suppose I have a DataFrame with some NaN
s:
>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
0 1 2
0 1 2 3
1 4 NaN NaN
2 NaN NaN 9
我需要做的是将每个 NaN
替换为其上方同一列中的第一个非 NaN
值.假定第一行将永远不包含 NaN
.因此,对于前面的示例,结果将是
What I need to do is replace every NaN
with the first non-NaN
value in the same column above it. It is assumed that the first row will never contain a NaN
. So for the previous example the result would be
0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
我可以逐列,逐个元素地循环遍历整个DataFrame并直接设置值,但是是否有一种简单的方法(最佳无循环方法)来实现这一点?
I can just loop through the whole DataFrame column-by-column, element-by-element and set the values directly, but is there an easy (optimally a loop-free) way of achieving this?
推荐答案
您可以使用 fillna
方法,并将该方法指定为 ffill
(正向填充):
You could use the fillna
method on the DataFrame and specify the method as ffill
(forward fill):
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
此方法...
相反,还有一个 bfill
方法.
此方法不会就地修改DataFrame-您需要将返回的DataFrame重新绑定到变量,或者指定 inplace = True
:
This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify inplace=True
:
df.fillna(method='ffill', inplace=True)
这篇关于如何用pandas DataFrame中的上一个或下一个值替换NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!