Home > Net >  What is the most efficient way to swap the values of two columns of a 2D list in python when the num
What is the most efficient way to swap the values of two columns of a 2D list in python when the num

Time:03-09

for example if I have an original list:

A B 
1 3
2 4

to be turned into

A B 
3 1
4 2

CodePudding user response:

two cents worth:

3 ways to do it

  1. you could add a 3rd column C, copy A to C, then delete A. This would take more memory.
  2. you could create a swap function for the values in a row, then wrap it into a loop.
  3. you could just swap the labels of the columns. This is probably the most efficient way.

CodePudding user response:

You could use rename:

df2 = df.rename(columns={'A': 'B', 'B': 'A'})

output:

   B  A
0  1  3
1  2  4

If order matters:

df2 = df.rename(columns={'A': 'B', 'B': 'A'})[df.columns]

output:

   A  B
0  3  1
1  4  2

CodePudding user response:

You can also just simple use masking to change the values.

import pandas as pd
df = pd.DataFrame({"A":[1,2],"B":[3,4]})

df[["A","B"]] = df[["B","A"]].values

df

   A  B
0  3  1
1  4  2

CodePudding user response:

Use DataFrame.rename with dictionary for swapping columnsnames, last check orcer by selecting columns:

df = df.rename(columns=dict(zip(df.columns, df.columns[::-1])))[df.columns]
print (df)
   A  B
0  3  1
1  4  2

CodePudding user response:

for more than 2 columns:

df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9], 'D':[10,11,12]})
print(df)
'''
   A  B  C   D
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12
'''
df = df.set_axis(df.columns[::-1],axis=1)[df.columns]
print(df)
'''
    A  B  C  D
0  10  7  4  1
1  11  8  5  2
2  12  9  6  3
  • Related