假设我有以下数据集
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')
现在我想replace
用dct
计算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
谢谢你的帮助。你知道吗
此行为不是预期的,被认为是一个bug。你知道吗
This is the Github issue首先确定了行为,并将其添加为
pandas 0.24.0
的里程碑。我可以确认在Github上的当前版本中,替换工作正常。你知道吗Here is the PR containing the fix.
这是因为
replace
一直在应用字典使用给定的
dct
'u'
->;'y'
然后'y'
->;'u'
。你知道吗相关问题 更多 >
编程相关推荐