python - Pandas 用 dict 输入“替换”会根据 dict 顺序返回不同的结果(其中 dict 没有顺序)
问题描述
我有一个,或的pandas
Series
值。True
False
None
import pandas as pd
s = pd.Series([True, True, False, False, None, None])
我想分别将其替换为 1、-1 或 0。
但是当我运行.replace
命令时,我看到结果取决于我定义字典的方式。例如,如果我使用相同的键和值定义以下两个字典,它们的行为应该相同:
dict_1 = {None: 0, False: -1, True: 1}
dict_2 = {False: -1, None: 0, True: 1}
但是,他们没有!
s.replace(dict_1)
输出
0 1
1 1
2 -1
3 -1
4 -1
5 -1
和
s.replace(dict_2)
返回
0 1
1 1
2 -1
3 -1
4 0
5 0
这是什么原因?以及如何确保获得我想要的行为(第二种情况,如 with dict_2
)?
[已编辑:python 3.6.1、pandas 0.21.1 中存在问题。根据 – @Andrey Berenda,问题不会在 python 3.7 和 pandas 0.25 中重现]
解决方案
使用Series.map
:
mapping = {None: 0, False: -1, True: 1}
s.map(mapping)
0 1
1 1
2 -1
3 -1
4 0
5 0
dtype: int64
或者使用替换,也可以:
s.replace({True: 1, False: -1, None: 0})
0 1
1 1
2 -1
3 -1
4 0
5 0
dtype: int64
推荐阅读
- r - 无法理解列表是如何构建的
- spring-integration - Sprint 集成流程无法启动
- haskell - 如何将字符与 Haskell 中的数字进行比较?
- spring-boot - 弹簧靴找不到配置文件
- reactjs - 如何使用 Axios 从 React 功能组件向 localhost 服务器发出的 get 请求中访问数据?
- filtering - 我可以关闭 Tableau 筛选器中的条件吗?
- android - Recylerview 项目有时只注册点击
- jquery - 在来自浏览器的 POST 请求之前,是否验证了 HTTP 标头中的内容类型?
- windows - _vimrc 他的主目录覆盖 $VIM 中的 _vimrc
- elasticsearch - elasticsearch 找不到命令行工具