简体   繁体   English

用下一次出现的非 np.nan 值的值填充 np.nan 值

[英]Fill in np.nan values with the value of the next occurrance of non np.nan value

I am trying to figure out how to replace all nan values under a certain condition.我试图弄清楚如何在特定条件下替换所有 nan 值。 If a value is nan, I would like to have it replaced with the date to the right side of it in it's specific list.如果值是 nan,我希望将其替换为特定列表中右侧的日期。 If there are no date value to the right of the nan value, I would like to leave it as is.如果 nan 值右侧没有日期值,我想保持原样。

Here is my starting dataframe.这是我的起始 dataframe。

mydf = [['2019-01-30', nan, nan, nan, '2020-03-09'],
        ['2018-11-29', nan, '2019-06-24', '2019-12-18', '2020-02-11'],
        [nan, nan, '2020-02-25', nan, nan]]

I would like this to end up looking like this.我希望这最终看起来像这样。

mydf = [['2019-01-30', '2020-03-09', '2020-03-09', '2020-03-09', '2020-03-09'],
        ['2018-11-29', '2019-06-24', '2019-06-24', '2019-12-18', '2020-02-11'],
        ['2020-02-25', '2020-02-25', '2020-02-25', nan, nan]]

Here is my current attempt:这是我目前的尝试:

for i in range(0,len(mydf)):
    for j, k in enumerate(mydf[i]):
        if k is np.nan:
            mydf[i][j] = mydf[i][j+1]

mydf

but I receive an error.但我收到一个错误。 I can't seem to figure out how to stop the loop within each list once the remaining values in the list are all nan.一旦列表中的剩余值全部为 nan,我似乎无法弄清楚如何在每个列表中停止循环。

IndexError                                Traceback (most recent call last)
<ipython-input-247-3f0a1ce84ea0> in <module>
      2     for j, k in enumerate(mydf[i]):
      3         if k is np.nan:
----> 4             mydf[i][j] = mydf[i][j+1]
      5 
      6 mydf

IndexError: list index out of range

mydf
    [['2020-02-25', '2020-02-25', '2020-02-25', nan, nan],
     ['2018-11-29', nan, '2019-06-24', '2019-12-18', '2020-02-11'],
     ['2019-01-30', nan, nan, nan, '2020-03-09']]

You can do as desired.您可以根据需要进行操作。

mydf.fillna(method='ffill') 
mydf.fillna(method='bfill')

No need to do loop here.这里不需要循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM