DataFrame: if value in a cell, copy value to cells below it

天大地大妈咪最大 提交于 2021-02-10 14:47:39

问题


I'm working on a stock analysis program and need to find 'SPLIT' amounts from the 'UNP_action', and then copy the corresponding 'UNP_action_amount' to rows above it only.

I'm able to do this in a complicated way via loops, but I'm wondering if there's a more efficient way to do this within Pandas.

Current:

Date        UNP_Adj_Close   UNP_action  UNP_action_amount
2008-05-23  31.83157        
2008-05-27  33.032365       
2008-05-28  32.965423       
2008-05-29  33.61812        SPLIT       0.5
2008-05-30  34.438176       

Desired:

Date    UNP_Adj_Close   UNP_action  UNP_action_amount
2008-05-23  31.83157                0.5
2008-05-27  33.032365               0.5
2008-05-28  32.965423               0.5
2008-05-29  33.61812    SPLIT       0.5
2008-05-30  34.438176

Any suggestions would be appreciated, thanks!


回答1:


If every split row has a corresponding value to fill with, you can just use fillna with the backfill method to propagate values backwards.

df.UNP_action_amount.fillna(method='backfill')

Demo

>>> df
   data
0   NaN
1   NaN
2   3.0
3   NaN
4   NaN
5   2.0
6   NaN
7   NaN
8   NaN

>>> df.data.fillna(method='backfill')
0    3.0
1    3.0
2    3.0
3    2.0
4    2.0
5    2.0
6    NaN
7    NaN


来源:https://stackoverflow.com/questions/42352669/dataframe-if-value-in-a-cell-copy-value-to-cells-below-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!