pandas 熊猫用以前的非零值替换零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33261359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:05:30  来源:igfitidea点击:

pandas replace zeros with previous non zero value

pythonpandas

提问by Gabriel

I have the following dataframe:

我有以下数据框:

index = range(14)
data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1]
df = pd.DataFrame(data=data, index=index, columns = ['A'])

How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?.

如何使用Pandas用以前的非零值填充零?是否有不只是“NaN”的fillna?

The output should look like:

输出应如下所示:

[1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1]

(This question was asked before here Fill zero values of 1d numpy array with last non-zero valuesbut he was asking exclusively for a numpy solution)

(这个问题在这里之前被问到用最后一个非零值填充 1d numpy 数组的零值,但他专门要求一个 numpy 解决方案)

回答by Zero

You can use replacewith method='ffill'

你可以用replacemethod='ffill'

In [87]: df['A'].replace(to_replace=0, method='ffill')
Out[87]:
0     1
1     1
2     1
3     2
4     2
5     4
6     6
7     8
8     8
9     8
10    8
11    8
12    2
13    1
Name: A, dtype: int64

To get numpy array, work on values

要获得 numpy 数组,请继续 values

In [88]: df['A'].replace(to_replace=0, method='ffill').values
Out[88]: array([1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1], dtype=int64)

回答by Abhay Bh

This is a better answer to the previous one, since the previous answer returns a dataframe which hides all zero values.

这是对前一个更好的答案,因为前一个答案返回一个隐藏所有零值的数据帧。

Instead, if you use the following line of code -

相反,如果您使用以下代码行 -

df['A'].mask(df['A'] == 0).ffill(downcast='infer')

Then this resolves the problem. It replaces all 0 values with previous values.

然后这解决了问题。它用以前的值替换所有 0 值。