【问题标题】:Ordering Headers in a DataFrame using Python使用 Python 对 DataFrame 中的标头进行排序
【发布时间】:2013-05-22 05:32:26
【问题描述】:

如何对数据帧的标头进行排序。

from pandas import *
import pandas
import numpy as np
df2 = DataFrame({'ISO':['DE','CH','AT','FR','US'],'Country': 
['Germany','Switzerland','Austria','France','United States']})
print df2

我默认得到的结果是这样的:

         Country ISO
0        Germany  DE
1    Switzerland  CH
2        Austria  AT
3         France  FR
4  United States  US

但我认为 ISO 会在 Country 之前,因为这是我在数据框中创建它的顺序。好像是按字母顺序排序的?

我如何在内存中设置这个简单的表,以便以后按我喜欢的列顺序在关系查询中使用。每次我引用数据框时,我都不想对列进行排序。

我的第一个编码帖子,永远。

【问题讨论】:

    标签: python header dataframe pandas


    【解决方案1】:

    dict 没有排序,您可以使用 columns 参数来强制执行。如果没有提供 columns,则默认排序确实是按字母顺序。

    In [2]: df2 = DataFrame({'ISO':['DE','CH','AT','FR','US'],
       ...:                  'Country': ['Germany','Switzerland','Austria','France','United States']},
       ...:                  columns=['ISO', 'Country'])
    
    In [3]: df2
    Out[3]:
      ISO        Country
    0  DE        Germany
    1  CH    Switzerland
    2  AT        Austria
    3  FR         France
    4  US  United States
    

    【讨论】:

      【解决方案2】:

      Python dict 是无序的。密钥不是按照您声明或附加到它的顺序存储的。您给 DataFrame 作为参数的 dict 具有 DataFrame 认为理所当然的任意顺序。

      您有多种选择来规避该问题:

      1. 如果您确实需要字典作为输入,请使用 OrderedDict 对象而不是 dict

        df2 = DataFrame(OrderedDict([('ISO',['DE','CH','AT','FR','US']),('Country',['Germany','Switzerland','Austria','France','United States'])]))

      2. 如果您一开始不依赖字典,则使用声明列的参数调用DataFrame

        df2 = DataFrame({'ISO':['DE','CH','AT','FR','US'],'Country': ['Germany','Switzerland','Austria','France','United States']}, columns=['ISO', 'Country'])

      【讨论】:

        猜你喜欢
        • 2019-03-06
        • 2016-05-31
        • 2022-01-21
        • 2019-11-28
        • 2021-04-20
        • 1970-01-01
        • 2018-05-18
        • 2021-08-13
        • 2016-12-21
        相关资源
        最近更新 更多