问题
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