'What is the most efficient way to swap the values of two columns of a 2D list in python when the number of rows is in the tens of thousands?
for example if I have an original list:
A B
1 3
2 4
to be turned into
A B
3 1
4 2
Solution 1:[1]
two cents worth:
3 ways to do it
- you could add a 3rd column C, copy A to C, then delete A. This would take more memory.
- you could create a swap function for the values in a row, then wrap it into a loop.
- you could just swap the labels of the columns. This is probably the most efficient way.
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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
Solution 5:[5]
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
Solution 6:[6]
I assume that your list is like this:
my_list = [[1, 3], [2, 4]]
So you can use this code:
print([[each_element[1], each_element[0]] for each_element in my_list])
The output is:
[[3, 1], [4, 2]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FamishedAtom |
| Solution 2 | mozway |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | SergFSM |
| Solution 6 | Happy Ahmad |
