[英]How to do a fillna with zero values until data appears in each column, then use the forward fill for each column in pandas data frame
I have the following data frame,我有以下数据框,
date x1 x2 x3
2001-01-01 nan 0.4 0.1
2001-01-02 nan 0.3 nan
2021-01-03 nan nan 0.5
...
2001-05-05 nan 0.1 0.2
2001-05-06 0.1 nan 0.3
...
So I want to first fill all nan values with zero until the first data point appears in each column, after that, I want the rest of the rows to use the fowardfill function.所以我想首先用零填充所有 nan 值,直到第一个数据点出现在每列中,之后,我希望行的 rest 使用 fowardfill function。
So the above data frame should look like this,所以上面的数据框应该是这样的,
date x1 x2 x3
2001-01-01 0 0.4 0.1
2001-01-02 0 0.3 0.1
2021-01-03 0 0.3 0.5
...
2001-05-05 0 0.1 0.2
2001-05-06 0.1 0.1 0.3
...
If I do fillna with 0 first then do forwardfill, like this,如果我先用 0 进行填充,然后再进行前向填充,就像这样,
df = df.fillna(0)
df = df.ffill()
I just get all the na values to be zero, and I am unable to do ffill for the parts where the data starts.我只是让所有 na 值都为零,并且我无法填充数据开始的部分。
Is there a way to do the ffill the way I want?有没有办法按照我想要的方式完成?
Reverse the logic:反转逻辑:
out = df.ffill().fillna(0)
print(out)
# Output
date x1 x2 x3
0 2001-01-01 0.0 0.4 0.1
1 2001-01-02 0.0 0.3 0.1
2 2021-01-03 0.0 0.3 0.5
3 2001-05-05 0.0 0.1 0.2
4 2001-05-06 0.1 0.1 0.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.