【问题标题】:pandas - Sorting Columns in a custom orderpandas - 按自定义顺序对列进行排序
【发布时间】:2021-12-01 19:17:03
【问题描述】:

我有一个每天生成的 Pandas 数据框,每次生成时,数据框中的列列表可能会有所不同。

我正在尝试查看是否可以对列存储为特定格式的 Dataframe 的最终输出的顺序进行排序。如果存在新列,则将它们放在最后。

下面是我尝试构建这个最终输出的方式

expected_columns = ['cust_id','cost_id','sale_id','prod_id']

示例数据框列:

['customer_name','cust_id','sale_id','sale_time']

我希望上面的 Dataframe 结构如下:

['cust_id','sale_id','customer_name','sale_time']

基本上expected_columns中的列优先,然后将Dataframe中的其他列作为新Dataframe的连续列。

【问题讨论】:

    标签: python pandas sorting


    【解决方案1】:

    第一个想法是使用列表理解并通过+ 加入列表:

    expected_columns = ['cust_id','cost_id','sale_id','prod_id']
    
    df = pd.DataFrame(columns=['customer_name','cust_id','sale_id','sale_time'])
    
    expected_columns = ['cust_id','cost_id','sale_id','prod_id']
    new1 = [c for c in df.columns if c in expected_columns]
    new2 = [c for c in df.columns if c not in expected_columns]
    
    new = new1 + new2
    print (new)
    ['cust_id','sale_id','customer_name','sale_time']
    

    或者使用Index.intersection 和Index.difference:

    expected_columns = ['cust_id','cost_id','sale_id','prod_id']
    
    new = (df.columns.intersection(expected_columns, sort=False).tolist() + 
           df.columns.difference(expected_columns, sort=False).tolist())
    

    如果通过expected_columns 在输出中排序也很重要:

    new = (pd.Index(expected_columns).intersection(df.columns, sort=False).tolist() +
           df.columns.difference(expected_columns, sort=False).tolist())
    

    差异改变样本数据:

    expected_columns = ['sale_id','cost_id','cust_id','prod_id']
    
    
    df = pd.DataFrame(columns=['customer_name','cust_id','sale_id','sale_time'])
    
    
    new = (pd.Index(expected_columns).intersection(df.columns, sort=False).tolist() +
           df.columns.difference(expected_columns, sort=False).tolist())
    print (new)
    ['sale_id', 'cust_id', 'customer_name', 'sale_time']
    
    
    new = (df.columns.intersection(expected_columns, sort=False).tolist() + 
           df.columns.difference(expected_columns, sort=False).tolist())
    print (new)
    ['cust_id', 'sale_id', 'customer_name', 'sale_time']
    

    最后更改列使用顺序:

    df = df[new]
    

    【讨论】:

    • @KevinNash - 最后使用df = df[new]
    猜你喜欢
    • 2019-05-28
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多