Python – Swap values in multiple dataframes

  • A+
Category:Languages

I have a DataFrame like this

id  val1   val2 0    A      B 1    B      B 2    A      A 3    A      A 

And I would like swap values such as:

id  val1   val2 0    B      A 1    A      A 2    B      B 3    B      B 

I need to consider that the df could have other columns that I would like to keep unchanged.

 


You can use pd.DataFrame.applymap with a dictionary:

d = {'B': 'A', 'A': 'B'}  df = df.applymap(d.get).fillna(df)  print(df)    id val1 val2 0  0    B    A 1  1    A    A 2  2    B    B 3  3    B    B 

For performance, in particular memory usage, you may wish to use categorical data:

for col in df.columns[1:]:     df[col] = df[col].astype('category')     df[col] = df[col].cat.rename_categories(d) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: