gpt4 book ai didi

python - 如何通过指定关键字对 pandas 数据框中的列名称进行排序

转载 作者:行者123 更新时间:2023-12-01 06:35:39 24 4
gpt4 key购买 nike

listdict 格式指定任意关键字,如下
是否可以对数据框中的列进行排序?

df = pd.DataFrame ({  
"col_cc_7": [0, 0, 0],
"col_aa_7": [1, 1, 1],
"col_bb_7": [2, 2, 2]})

# before
col_cc_7, col_aa_7, col_bb_7
0, 1, 2
0, 1, 2
0, 1, 2

# sort
custom_sort_key = ["aa", "bb", "cc"]
# ... sort codes ...

# after
col_aa_7, col_bb_7, col_cc_7
1, 2, 0
1, 2, 0
1, 2, 0

最佳答案

我们可以按中间值进行拆分并创建列的字典,然后在将其分配回之前应用排序。我添加了一些不属于您排序的额外列,以显示它们会发生什么。

df = pd.DataFrame ({  
"col_cc_7": [0, 0, 0],
"col_aa_7": [1, 1, 1],
"col_bb_7": [2, 2, 2],
"col_ee_7": [2, 2, 2],
"col_dd_7": [2, 2, 2]})

custom_sort_key = ["bb", "cc", "aa"]

col_dict = dict(zip(df.columns,[x.split('_')[1] for x in df.columns.tolist()]))

#{'col_cc_7': 'cc',
# 'col_aa_7': 'aa',
# 'col_bb_7': 'bb',
# 'col_ee_7': 'ee',
# 'col_dd_7': 'dd'}
d = {v:k for k,v in enumerate(custom_sort_key)}


# this will only work on python 3.6 +
new_cols = dict(sorted(col_dict.items(), key=lambda x: d.get(x[1], float('inf'))))

df[new_cols.keys()]
col_bb_7 col_cc_7 col_aa_7 col_ee_7 col_dd_7
0 2 0 1 2 2
1 2 0 1 2 2
2 2 0 1 2 2

关于python - 如何通过指定关键字对 pandas 数据框中的列名称进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59683166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com