Pandas中DataFrame交換列順序的方法實現(xiàn)
一、獲取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)
['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',...]
二、改變列標簽為指定順序
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) cols.insert(0, cols.pop(cols.index('ps_state-running'))) print(cols)
這里改變第一列和第二列的位置順序,用到了python list中的兩個方法
insert方法:
1.功能
insert()函數(shù)用于將指定對象插入列表的指定位置。
2.語法
list.insert(index, obj)
3.參數(shù)
index: 對象obj需要插入的索引位置。
obj: 插入列表中的對象。
pop() 函數(shù)用于移除列表中的一個元素(默認最后一個元素),并且返回該元素的值
三、利用loc獲取新的DataFrame,拷貝交換順序后的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) cols.insert(0, cols.pop(cols.index('ps_state-running'))) print(cols) data = dataset.loc[:, cols]
四、保存csv覆蓋原來的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) cols.insert(0, cols.pop(cols.index('ps_state-running'))) print(cols) data = dataset.loc[:, cols] data.to_csv(file_path, index=False)
五、也可以這樣
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) cols.insert(0, cols.pop(cols.index('ps_state-running'))) print(cols) dataset.loc[:, ['ps_state-running', 'ps_state-stopped']] = dataset[['ps_state-stopped', 'ps_state-running']].values dataset.columns = cols dataset.to_csv(file_path, index=False)
到此這篇關于Pandas中DataFrame交換列順序的方法實現(xiàn)的文章就介紹到這了,更多相關Pandas DataFrame交換列順序內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Selenium結合BeautifulSoup4編寫簡單的python爬蟲
這篇文章主要介紹了Selenium結合BeautifulSoup4編寫簡單的python爬蟲,幫助大家更好的理解和學習python 爬蟲的相關知識,感興趣的朋友可以了解下2020-11-11解決django的template中如果無法引用MEDIA_URL問題
這篇文章主要介紹了解決django的template中如果無法引用MEDIA_URL問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Python selenium 自動化腳本打包成一個exe文件(推薦)
這篇文章主要介紹了Python selenium 自動化腳本打包成一個exe文件,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01Python使用tablib生成excel文件的簡單實現(xiàn)方法
這篇文章主要介紹了Python使用tablib生成excel文件的方法,結合實例形式分析了tablib模塊的相關使用技巧,需要的朋友可以參考下2016-03-03Python圖像處理庫crop()函數(shù)?thumbnail方法使用詳解
這篇文章主要為大家介紹了Python圖像處理庫crop()函數(shù)?thumbnail方法使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04