是否逐行替换并将两次覆盖dict中的值?

WeN*_*Ben 6 python pandas

假设我有以下数据集

lst = ['u', 'v', 'w', 'x', 'y']
lst_rev = list(reversed(lst))
dct = dict(zip(lst, lst_rev))

df = pd.DataFrame({'A':['a', 'b', 'a', 'c', 'a'],
                   'B':lst},
                   dtype='category')
Run Code Online (Sandbox Code Playgroud)

现在我想要replacedf中的B列值dct

我知道我能做到

df.B.map(dct).fillna(df.B)

得到预期的输出,但当我测试时replace(根据我的想法更直接),我失败了

输出显示如下

df.B.replace(dct)
Out[132]: 
0    u
1    v
2    w
3    v
4    u
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)

哪个不同于

df.B.map(dct).fillna(df.B)
Out[133]: 
0    y
1    x
2    w
3    v
4    u
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)

我能想到这种情况发生的原因,但为什么呢?

0    u --> change to y then change to u
1    v --> change to x then change to v
2    w
3    v
4    u
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助.

piR*_*red 6

这是因为replace继续应用字典

df.B.replace({'u': 'v', 'v': 'w', 'w': 'x', 'x': 'y', 'y': 'Hello'})

0    Hello
1    Hello
2    Hello
3    Hello
4    Hello
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)

随着给定dct 'u'- > 'y'然后'y'- > 'u'.

  • 我在他们的github页面上提交了一个问题,希望我得到一个回复​​,也许是有意的 (2认同)

use*_*203 5

此行为不是故意的,并且被认为是错误。

这是Github问题,它首先确定了行为,并将其添加为的里程碑pandas 0.24.0。我可以在Github上确认按当前版本的预期进行替换。

这是包含此修复程序的PR。