python - 替换 pandas 系列中的值,其中要替换的元素包含要替换的元素的一部分

标签 python python-3.x pandas replace

例如,我想将 2/8/2014 0:00 替换为 2014 并将 1/29/2015 0:00 替换为2015 及以后。

2014               180657
2015               153837
2014                72395
2012                69708
2013                61364
2015                54117
2013                 3313
2012                 1076
2/8/2014 0:00           2
7/3/2014 0:00           2
1/29/2015 0:00          2
9/1/2014 0:00           2
11/22/2014 0:00         2
10/16/2014 0:00         2

最佳答案

从系列开始,ser:

2014               180657
2015               153837
2014                72395
2012                69708
2013                61364
2015                54117
2013                 3313
2012                 1076
2/8/2014 0:00           2
7/3/2014 0:00           2
1/29/2015 0:00          2
9/1/2014 0:00           2
11/22/2014 0:00         2
10/16/2014 0:00         2
dtype: int64

您可以将索引转换为日期时间并提取年份:

ser.index = pd.to_datetime(ser.index, errors='coerce').year
ser

2014    180657
2015    153837
2014     72395
2012     69708
2013     61364
2015     54117
2013      3313
2012      1076
2014         2
2014         2
2015         2
2014         2
2014         2
2014         2
dtype: int64

如果这引入了 NaN,您可以通过以下方式消除它们

ser = ser[ser.index.notnull()]
ser.index = ser.index.astype('int')

如果你想按年份分组,你可以按索引分组:

ser.groupby(level=0).sum()
Out: 
2012     70784
2013     64677
2014    253062
2015    207956
dtype: int64

关于python - 替换 pandas 系列中的值,其中要替换的元素包含要替换的元素的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541508/

相关文章:

python - 安排启动 EC2 实例并在其中运行 python 脚本

python - session 未创建异常 : Message: Unable to create new service: ChromeDriverService with ChromeDriver and SeleniumGrid through Python

python-3.x - 命令行或 .exe 中的 Python 程序给出 MemoryError,但在 Spyder IDE 中工作正常

python - 如何在python的列中选择一个n值

python Pandas : Denormalize data from one data frame into another

python - 创建一个正常运行的响应对象

python - 将 Mongodb 导入 CSV - 删除重复项

python-3.x - 带有 pytest 的异步装置

python - 是否有任何理由不在 Python 中混合使用多处理和线程模块

python - 从 Python 函数调用 `dt.` 类型