首页 > 解决方案 > Pandas 用 dict 输入“替换”会根据 dict 顺序返回不同的结果(其中 dict 没有顺序)

问题描述

我有一个,或的pandas Series值。TrueFalseNone

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 中重现]

标签: pythonpandasdictionary

解决方案


使用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

推荐阅读