Search code examples
pythonpandasnumpydata-analysis

How to interchange the values between two columns in python


Suppose I am having a dataframe like:

 S.NO Length  Width  Height   
  1    200      100    100 
  2    250      150    150
  3    200      250    170

Here in the 3rd row, Width is greater than Length, So I want to interchange those two values in the dataset where the Width is greater than Length like this

S.NO Length  Width  Height
  1    200      100    100     
  2    250      150    150
  3    250      200    170 

Is it possible in pandas or if there is no solution for this, what is the best case to implement this?


Solution

  • Let us try with np.sort then assign

    df[['Length','Width']] = np.sort(df[['Length','Width']].values, axis=1)[:,::-1]
    df
    Out[326]: 
       S.NO  Length  Width  Height
    0     1     200    100     100
    1     2     250    150     150
    2     3     250    200     170