如何用以前的值替换 pandas 系列中的某些值? [英] How to replace certain values in pandas Series with its previous value?

查看:47
本文介绍了如何用以前的值替换 pandas 系列中的某些值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的熊猫系列对象s:

<预><代码>>>>秒日期2020-03-26 19.722020-03-27 19.752020-03-30 19.432020-03-31 19.692020-04-01 --2020-04-06 20.032020-04-07 20.452020-04-08 21.002020-04-09 --2020-04-10 20.962020-04-13 20.752020-04-14 21.23名称:价格,数据类型:对象>>>s.values数组(['19.72', '19.75', '19.43', '19.69', '--', '20.03', '20.45','21.00', '20.82', '20.96', '20.75', '21.23'], dtype=object)

如何将 -- 替换为其以前的值?

我的意思是我想将 s 转换成这样:

日期2020-03-26 19.722020-03-27 19.752020-03-30 19.432020-03-31 19.692020-04-01 19.692020-04-06 20.032020-04-07 20.452020-04-08 21.002020-04-09 21.002020-04-10 20.962020-04-13 20.752020-04-14 21.23名称:价格,数据类型:对象

属于2020-04-01--被替换为2020-03-31的值,即<代码>19.69.

解决方案

您可以将那些 -- 替换为 NaN 并且只需 ffill:

df.replace('--', float('nan')).ffill()日期2020-03-26 19.722020-03-27 19.752020-03-30 19.432020-03-31 19.692020-04-01 19.692020-04-06 20.032020-04-07 20.452020-04-08 21.002020-04-09 21.002020-04-10 20.962020-04-13 20.752020-04-14 21.23

或者你也可以使用 pd.to_numeric,强制那些不能是大小写的浮动:

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

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.

解决方案

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()

这篇关于如何用以前的值替换 pandas 系列中的某些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆