如何更改 Pandas DataFrame 列的顺序?
要更改DataFrame列的顺序,我们可以采取以下步骤-
步骤
生成二维、大小可变、潜在异构的表格数据df。
打印输入数据帧。
使用df获取DataFrame列的列表。columns.tolist()
更改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:\n", df
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]
print "After changing the order: \n", 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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短