首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >按字母和数字顺序对数据栏进行排序

按字母和数字顺序对数据栏进行排序
EN

Stack Overflow用户
提问于 2021-10-20 12:53:55
回答 1查看 154关注 0票数 1

我想通过按字母顺序和数字顺序对数据的列进行重新索引。

在我的dataframe df中,我的列名为:

第一轮位置,第二轮位置,第一轮得分,第二轮得分,第一轮价格,第二轮价格,……,第十轮位置,第十轮得分,第十轮价格

我希望按以下方式订购:

第1轮的位置,第1轮的价格,第1轮的分数,第2轮的位置,第2轮的价格,第2轮的分数,第3轮的位置,第3轮的价格,第3轮的分数,第10轮的位置,第10轮的价格,第10轮的分数

我尝试了以下几点:

代码语言:javascript
运行
复制
df.reindex(sorted(df.columns, key=lambda x: float(x[1:])), axis=1) 

但没有运气,因为列名是字符串。

谢谢你抽出时间阅读我的问题并帮助我。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-20 13:14:48

一旦将列名按其自然顺序排序,就可以使用[]索引重新排序这些列。

代码语言:javascript
运行
复制
import pandas as pd
import natsort

df = pd.DataFrame({'A2': [1, 2, 3],
               'B1': [4, 5, 6],
               'A1': [7, 8, 9]})

# sort the column names
col_names = df.columns
sorted_col_names = natsort.natsorted(col_names)

# re-order the columns
df = df[sorted_col_names]
print(df)

输出:

代码语言:javascript
运行
复制
   A1  A2  B1
0   7   1   4
1   8   2   5
2   9   3   6

How to sort alpha numeric set in python的答案中有几种排序α-数字值的选项。我测试了natsort库,它与您的输入一起工作。

代码语言:javascript
运行
复制
columns = ['Round 1 Position', 'Round 2 Position', 'Round 1 Score', 'Round 2 Score', 'Round 1 Price',
           'Round 2 Price', 'Round 10 Position', 'Round 10 Score', 'Round 10 Price']
columns_s = natsort.natsorted(columns)
print(columns_s)

输出:

代码语言:javascript
运行
复制
['Round 1 Position', 'Round 1 Price', 'Round 1 Score', 'Round 2 Position', 'Round 2 Price', 'Round 2 Score', 'Round 10 Position', 'Round 10 Price', 'Round 10 Score']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69646359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档