How to replace certain values in pandas Series with its previous value?

戏子无情 提交于 2021-02-17 06:08:42

问题


I have a pandas Series object s like this:

>>> s
date
2020-03-26    19.72
2020-03-27    19.75
2020-03-30    19.43
2020-03-31    19.69
2020-04-01       --
2020-04-06    20.03
2020-04-07    20.45
2020-04-08    21.00
2020-04-09       --
2020-04-10    20.96
2020-04-13    20.75
2020-04-14    21.23
Name: price, dtype: object

>>> s.values
array(['19.72', '19.75', '19.43', '19.69', '--', '20.03', '20.45',
       '21.00', '20.82', '20.96', '20.75', '21.23'], dtype=object)

How can I replace -- with its previous value?

I mean I want s to be converted to this:

date
2020-03-26    19.72
2020-03-27    19.75
2020-03-30    19.43
2020-03-31    19.69
2020-04-01    19.69
2020-04-06    20.03
2020-04-07    20.45
2020-04-08    21.00
2020-04-09    21.00
2020-04-10    20.96
2020-04-13    20.75
2020-04-14    21.23
Name: price, dtype: object

The -- that belongs to 2020-04-01 is replaced with 2020-03-31's value, which is 19.69.


回答1:


You could replace those -- to NaN and just ffill:

df.replace('--', float('nan')).ffill()

           date
2020-03-26  19.72
2020-03-27  19.75
2020-03-30  19.43
2020-03-31  19.69
2020-04-01  19.69
2020-04-06  20.03
2020-04-07  20.45
2020-04-08  21.00
2020-04-09  21.00
2020-04-10  20.96
2020-04-13  20.75
2020-04-14  21.23

Or you could also use pd.to_numeric, coercing those that cannot be case to float:

pd.to_numeric(df.date, errors='coerce').ffill()


来源:https://stackoverflow.com/questions/61253066/how-to-replace-certain-values-in-pandas-series-with-its-previous-value

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