如何更改 Pandas DataFrame 列的順序?
若要更改 DataFrame 列的順序,我們可以執行以下步驟 -
步驟
建立二維、大小可變、潛在不同質的表格資料 df。
列印輸入 DataFrame。
使用 df.columns.tolist() 獲取 DataFrame 列列表
更改 DataFrame 列的順序。
修改 DataFrame 列的順序。
更改列順序後列印 DataFrame。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:
", df
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]
print "After changing the order:
", df輸出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 After changing the order: z x y 0 4 5 4 1 1 2 1 2 5 1 5 3 0 9 10
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP