You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas对CSV文件指定两列分别按升降序排序?

解决方案

你的核心问题是原函数对所有列统一使用降序排序,没有区分不同列的排序方向。要实现指定列按不同规则独立排序,只需针对目标列单独设置排序逻辑即可,无需遍历所有列。

修改后的代码如下:

import pandas as pd  

# 读取并重命名数据
bus1_data = pd.read_csv("p1Bus1Data.csv", header=None)
bus1_data.rename(columns={0: 'quantity bids', 1: 'price of bids', 2: 'quantity of offers', 3: 'price of offers'}, inplace=True)

bus2_data = pd.read_csv("p1Bus2Data.csv", header=None)
bus2_data.rename(columns={0: 'quantity bids', 1: 'price of bids', 2: 'quantity of offers', 3: 'price of offers'}, inplace=True)

def sort_columns_independently(df):
    # 复制原数据,避免修改原始数据集
    sorted_df = df.copy()
    # 对"price of bids"列按降序排序
    sorted_df['price of bids'] = sorted_df['price of bids'].sort_values(ascending=False).values
    # 对"price of offers"列按升序排序
    sorted_df['price of offers'] = sorted_df['price of offers'].sort_values(ascending=True).values
    # 若其他列也需排序,可在此添加对应规则,否则保持原顺序
    return sorted_df

sorted_bus1_data = sort_columns_independently(bus1_data)
sorted_bus2_data = sort_columns_independently(bus2_data)

关键说明

  • 针对目标列单独指定排序方向:ascending=False对应降序,ascending=True对应升序
  • 使用.values提取排序后的数组赋值,确保列内数据按规则重新排列,不破坏数据框结构
  • 先复制数据框再操作,避免误修改原始数据

如果需要对其他列也进行排序,只需在函数中添加对应代码即可,例如要让"quantity bids"按升序排列,可添加:

sorted_df['quantity bids'] = sorted_df['quantity bids'].sort_values(ascending=True).values

内容的提问来源于stack exchange,提问作者Juan Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:25:23