假设我有以下数据集
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)
感谢您的帮助.
这是因为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'.
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |