简体   繁体   English

如何使用零值进行填充,直到数据出现在每列中,然后对 pandas 数据帧中的每一列使用前向填充

[英]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.

相关问题 用pandas数据框中的一些默认值填充每个列组合的值 - Fill the values with each column combination with some default values in pandas data frame 在 pandas 数据框中的每一行中找到非零值的列索引集 - find the set of column indices for non-zero values in each row in pandas' data frame 如何使用 pandas 数据框将数据框的每一列值添加到一张一张的新工作表中 - How to add each column of a data frame values in one by one new sheets using pandas data frame 如果列元素是一个集合,如何从 pandas 数据框列中获取每个值的计数? - How do I get count of each value from a pandas Data Frame column if the column elements is a set? 熊猫数据帧每一列的平均归一化 - mean normalization for each column of pandas data frame 如何通过map / apply在熊猫数据框上使用lambda函数,其中lambda为每一列取不同的值 - How to use lambda function on a pandas data frame via map/apply where lambda takes different values for each column 如何使用 for-looped print() 结果在 pandas 的数据框中填写新列? - How do I use the use the for-looped print() outcome to fill in a new column in my data frame in pandas? 如何将数据框的每一列附加到熊猫系列中? - How to append each column of a data-frame to a series in pandas? 如何用列值替换pandas数据框中的每个值? - How to replace each value in pandas data frame with column value? 如何在每列的熊猫数据框中找到不合适的数据类型? - How to find inappropriate datatype in pandas data frame for each column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM