Is replace row-wise and will overwrite the value within the dict twice?

2024/9/22 21:17:01

Assuming I have following data set

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

Now I want to replace the value of column B in df by dct

I know I can do

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

to get the expected out put , but when I test with replace (which is more straightforward base on my thinking ), I failed

The out put show as below

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

Which is different from the

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

I can think that the reason why this happen, But why ?

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

Appreciate your help.

Answer

It's because replace keeps applying the dictionary

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

With the given dct 'u' -> 'y' then 'y' -> 'u'.

https://en.xdnf.cn/q/71828.html

Related Q&A

Python requests, how to add content-type to multipart/form-data request

I Use python requests to upload a file with PUT method.The remote API Accept any request only if the body contains an attribute Content-Type:i mage/png not as Request Header When i use python requests…

Django Year/Month based posts archive

im new to Django and started an application, i did the models, views, templates, but i want to add some kind of archive to the bottom of the page, something like this http://www.flickr.com/photos/ion…

ValueError: You are trying to load a weight file containing 6 layers into a model with 0

I have a simple keras model. After the model is saved. I am unable to load the model. This is the error I get after instantiating the model and trying to load weights:Using TensorFlow backend. Tracebac…

cProfile with imports

Im currently in the process of learn how to use cProfile and I have a few doubts.Im currently trying to profile the following script:import timedef fast():print("Fast!")def slow():time.sleep(…

Python AWS Lambda 301 redirect

I have a lambda handler written in Python and I wish to perform a 301 redirect to the browser. I have no idea how I can configure the response Location header (or the status code) -- the documentation …

Google Authenticator code does not match server generated code

BackgroundIm currently working on a two-factor authentication system where user are able to authenticate using their smartphone. Before the user can make use of their device they need to verify it firs…

Gekko Non-Linear optimization, object type error in constraint function evaluating if statement

Im trying to solve a non-linear optimization problem. Ive duplicated my issue by creating the code below. Python returns TypeError: object of type int has no len(). How can I include an IF statement in…

Store large dictionary to file in Python

I have a dictionary with many entries and a huge vector as values. These vectors can be 60.000 dimensions large and I have about 60.000 entries in the dictionary. To save time, I want to store this aft…

Python: override __str__ in an exception instance

Im trying to override the printed output from an Exception subclass in Python after the exception has been raised and Im having no luck getting my override to actually be called.def str_override(self):…

How hide/show a field upon selection of a radio button in django admin?

models.pyfrom django.db import models from django.contrib.auth.models import UserSTATUS_CHOICES = ((1, Accepted),(0, Rejected),) class Leave(models.Model):----------------status = models.IntegerField(c…