首页 > 解决方案 > Python - 对表中每一行的值进行排序,并获得一个新的 Pandas 数据框,其中每行中的原始列索引/标签按排序顺序排列

问题描述

我只有一个像这样的csv格式的表格

日期 公司1 公司2 公司3
01.01.2020 1,01 0,9 1
02.01.2020 0,9 2,2 2
... ... ... ...
2020 年 10 月 24 日 1,02 1,01 1,03

现在我的目标是按降序对每一行进行排序。所以我终于得到了下表:

日期 1 2 3
01.01.2020 公司1 公司3 公司2
02.01.2020 公司2 公司3 公司1
... ... ... ...
2020 年 10 月 24 日 公司3 公司1 公司2

他们是用python做某事的简单方法吗?

标签: pythonpandassorting

解决方案


一种方法使用np.argsort

# get column names
columns = df.columns[1:].to_numpy()

# get sorted indices
indices = np.argsort(df.iloc[:, 1:] * -1, axis=1)

# create new DataFrame
res = pd.concat([df["Date"], pd.DataFrame(columns[indices], columns=range(1, 4))], axis=1)
print(res)

输出

         Date         1         2         3
0  01.01.2020  Company1  Company3  Company2
1  02.01.2020  Company2  Company3  Company1
2  24.10.2020  Company3  Company1  Company2

推荐阅读