创建如下数据框时(来自here的说明),列的顺序从“日,访客,跳出率”变为“跳出率,日,访客”
import pandas as pd
web_stats = {'Day':[1,2,3,4,5,6],
'Visitors':[43,34,65,56,29,76],
'Bounce Rate':[65,67,78,65,45,52]}
df = pd.DataFrame(web_stats)
给予:
Bounce Rate Day Visitors
0 65 1 43
1 67 2 34
2 78 3 65
3 65 4 56
4 45 5 29
5 52 6 76
如何保持秩序? (即日,访客,跳出率)
答案 0 :(得分:4)
一种方法是使用columns
<强>实施例强>
import pandas as pd
web_stats = {'Day':[1,2,3,4,5,6],
'Visitors':[43,34,65,56,29,76],
'Bounce Rate':[65,67,78,65,45,52]}
df = pd.DataFrame(web_stats, columns = ['Day', 'Visitors', 'Bounce Rate'])
print(df)
<强>输出:强>
Day Visitors Bounce Rate
0 1 43 65
1 2 34 67
2 3 65 78
3 4 56 65
4 5 29 45
5 6 76 52
答案 1 :(得分:2)
字体不被视为在Python&lt; 3.7。
中订购您可以改为使用collections.OrderedDict
:
from collections import OrderedDict
web_stats = OrderedDict([('Day', [1,2,3,4,5,6]),
('Visitors', [43,34,65,56,29,76]),
('Bounce Rate', [65,67,78,65,45,52])])
df = pd.DataFrame(web_stats)
答案 2 :(得分:0)
如果您不想编写列名,那么在您有多个键的情况下会很不方便
df = pd.DataFrame(web_stats, columns = web_stats.keys())