Swap column values based on a condition in pandas

2024/11/13 18:28:35

I would like to relocate columns by condition. In case country is 'Japan', I need to relocate last_name and first_name reverse.

df = pd.DataFrame([['France','Kylian', 'Mbappe'],['Japan','Hiroyuki', 'Tajima'],['Japan','Shiji', 'Kagawa'],['England','Harry', 'Kane'],['Japan','Yuya', 'Ohsako'],['Portuguese','Cristiano', 'Ronaldo']],columns=['country', 'first_name', 'last_name'])

Current output is

      country first_name last_name
0      France     Kylian    Mbappe
1       Japan   Hiroyuki    Tajima
2       Japan      Shiji    kagawa
3     England      Harry      Kane
4       Japan       Yuya    Ohsako
5  Portuguese  Cristiano   Ronaldo

I would like to make it following.

      country first_name last_name
0      France     Kylian    Mbappe
1       Japan     Tajima  Hiroyuki
2       Japan     Kagawa    Shinji
3     England      Harry      Kane
4       Japan     Ohsako      Yuya
5  Portuguese  Cristiano   Ronaldo

Any idea?

Answer

Use loc and swap the "first_name" and "last_name" values for rows whose "country" matches "Japan".

m = df['country'] == 'Japan'df.loc[m, ['first_name', 'last_name']] = (df.loc[m, ['last_name', 'first_name']].values)
df    country first_name last_name
0  France      Kylian     Mbappe  
1  Japan       Tajima     Hiroyuki
2  Japan       Kagawa     Shiji   
3  England     Harry      Kane    
4  Japan       Ohsako     Yuya    
5  Portuguese  Cristiano  Ronaldo 

Another option using rename and update:

mp = {'first_name': 'last_name', 'last_name': 'first_name'}
df.update(df.loc[m].rename(mp, axis=1))
dfcountry first_name last_name
0  France      Kylian     Mbappe  
1  Japan       Tajima     Hiroyuki
2  Japan       Kagawa     Shiji   
3  England     Harry      Kane    
4  Japan       Ohsako     Yuya    
5  Portuguese  Cristiano  Ronaldo 
https://en.xdnf.cn/q/72005.html

Related Q&A

How to improve performance on a lambda function on a massive dataframe

I have a df with over hundreds of millions of rows.latitude longitude time VAL 0 -39.20000076293945312500 140.80000305175781250000 1…

How to detect if text is rotated 180 degrees or flipped upside down

I am working on a text recognition project. There is a chance the text is rotated 180 degrees. I have tried tesseract-ocr on terminal, but no luck. Is there any way to detect it and correct it? An exa…

Infinite loops using for in Python [duplicate]

This question already has answers here:Is there an expression for an infinite iterator?(7 answers)Closed 5 years ago.Why does this not create an infinite loop? a=5 for i in range(1,a):print(i)a=a+1or…

How to print the percentage of zipping a file python

I would like to get the percentage a file is at while zipping it. For instance it will print 1%, 2%, 3%, etc. I have no idea on where to start. How would I go about doing this right now I just have the…

kafka-python read from last produced message after a consumer restart

i am using kafka-python to consume messages from a kafka queue (kafka version 0.10.2.0). In particular i am using KafkaConsumer type. If the consumer stops and after a while it is restarted i would lik…

Python lib to Read a Flash swf Format File

Im interested in using Python to hack on the data in Flash swf files. There is good documentation available on the format of swf files, and I am considering writing my own Python lib to parse that dat…

PyQt5 Signals and Threading

I watched a short tutorial on PyQt4 signals on youtube and am having trouble getting a small sample program running. How do I connect my signal being emitted from a thread to the main window?import cp…

Pythons hasattr sometimes returns incorrect results

Why does hasattr say that the instance doesnt have a foo attribute?>>> class A(object): ... @property ... def foo(self): ... ErrorErrorError ... >>> a = A() >>…

Pure python library to read and write jpeg format

guys! Im looking for pure python implementation of jpeg writing (reading will be nice, but not necessary) library. Ive founded only TonyJPEG library port at http://mail.python.org/pipermail/image-sig/2…

Conda - unable to completely delete environment

I am using Windows 10 (all commands run as administrator). I created an environment called myenv. Then I used conda env remove -n myenvNow, if I tryconda info --envsI only see the base environment. How…