我想通过按字母顺序和数字顺序对数据的列进行重新索引。
在我的dataframe df中,我的列名为:
第一轮位置,第二轮位置,第一轮得分,第二轮得分,第一轮价格,第二轮价格,……,第十轮位置,第十轮得分,第十轮价格
我希望按以下方式订购:
第1轮的位置,第1轮的价格,第1轮的分数,第2轮的位置,第2轮的价格,第2轮的分数,第3轮的位置,第3轮的价格,第3轮的分数,第10轮的位置,第10轮的价格,第10轮的分数
我尝试了以下几点:
df.reindex(sorted(df.columns, key=lambda x: float(x[1:])), axis=1)
但没有运气,因为列名是字符串。
谢谢你抽出时间阅读我的问题并帮助我。非常感谢!
发布于 2021-10-20 13:14:48
一旦将列名按其自然顺序排序,就可以使用[]
索引重新排序这些列。
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)
输出:
A1 A2 B1
0 7 1 4
1 8 2 5
2 9 3 6
在How to sort alpha numeric set in python的答案中有几种排序α-数字值的选项。我测试了natsort
库,它与您的输入一起工作。
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)
输出:
['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']
https://stackoverflow.com/questions/69646359
复制相似问题