是replace rowwise并将覆盖dict中的值两次吗?

2024-04-20 09:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下数据集

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

现在我想replacedct计算df中B列的值

我知道我能做到

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

这和

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

我可以认为这是为什么,但是为什么?你知道吗

0    u --> change to y then change to u
1    v --> change to x then change to v
2    w
3    v
4    u

谢谢你的帮助。你知道吗


Tags: to数据namemapdfobjectrevout
2条回答

此行为不是预期的,被认为是一个bug。你知道吗

This is the Github issue首先确定了行为,并将其添加为pandas 0.24.0的里程碑。我可以确认在Github上的当前版本中,替换工作正常。你知道吗

Here is the PR containing the fix.

这是因为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

使用给定的dct'u'->;'y'然后'y'->;'u'。你知道吗

相关问题 更多 >