SoFunction
Updated on 2025-03-02

Implementation of DataFrame swapping column order in Pandas

1. Get the DataFrame column tag

import pandas as pd 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv' 
dataset = pd.read_csv(file_path)
cols = list(dataset)

['ps_state-stopped', 'ps_state-running', 'ps_state-blocked', 'ps_state-paging', 'ps_state-sleeping', 'ps_state-zombies', 'fork_rate', 'cpu-2-system', 'cpu-2-nice', 'cpu-2-steal',...]

2. Change the column label to the specified order

import pandas as pd

file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
(0, (('ps_state-running')))
print(cols)

Here we change the position order of the first column and the second column, and use two methods in the python list

insert method:
1. Function
The insert() function is used to insert a specified object into a specified position in the list.
2. Syntax
(index, obj)
3. Parameters
index: The index position to be inserted in the object obj.
obj: Insert an object in the list.
The pop() function removes an element in the list (the last element by default) and returns the value of that element.

3. Use loc to obtain a new DataFrame, copy and exchange the DataFrame

import pandas as pd

file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
(0, (('ps_state-running')))
print(cols)
data = [:, cols]

4. Save csv overwrite the original csv

import pandas as pd
 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'

dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
(0, (('ps_state-running')))
print(cols)
data = [:, cols]
data.to_csv(file_path, index=False)

5. This is also possible

import pandas as pd
 
file_path = '/Users/Arithmetic/da-rnn-master/data/collectd67_power_after_test_smooth.csv'
 
dataset = pd.read_csv(file_path)
cols = list(dataset)
print(cols)
(0, (('ps_state-running')))
print(cols)
[:, ['ps_state-running', 'ps_state-stopped']] = dataset[['ps_state-stopped', 'ps_state-running']].values
 = cols
dataset.to_csv(file_path, index=False)

This is the end of this article about the implementation of the DataFrame exchange column order in Pandas. For more related content on Pandas DataFrame exchange column order, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!