python - 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做某事的简单方法吗?
解决方案
一种方法使用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
推荐阅读
- python - 需要帮助对客户评论和一串文本进行情绪分析
- go - syscall/js websocket 回调在非阻塞行为中不响应
- django - 使用 Django 处理动态模型/数据
- c - 在我的 C 代码中需要帮助 - 获得意外的输出
- javascript - 垫子步进器不适用于选择选项
- visual-studio - 如何在运行时根据地址确定 C++ 对象的类型?
- javascript - 在 Phaser 3 TypeError 中调用 this.scene.restart(): this.body is undefined
- html - 无法获取表格单元格值
- java - 打开 url 并发送标头值
- javascript - 为什么 lodash deepClone 不对 Function 属性进行深度克隆?