【问题标题】:Sort dataframe based on custom dictionary根据自定义字典对数据框进行排序
【发布时间】:2022-07-05 22:48:00
【问题描述】:

我拥有的数据框是:

df = pd.DataFrame(data={'Question':['Q2','Q2','Q1','Q1','Q1','Q3','Q3','Q3'],
                    'Answer':['Yes','No','$1 to $49','$100 to $200','$50 to $100','More than 5000','Less than 5000','Don't know']})

我想按QuestionAnswer 列对数据框进行排序。我创建了一个自定义字典,以便在按Answer 排序时使用,以便可以对分类值进行相应的排序。

answer_sort_order = {'$1 to $49': 0, '$50 to $100': 1, '$50 to $99': 2, '$100 to $200': 3,'More than 5000': 4, 'Less than 5000': 5, 'Don't Know': 6}

如何使用它来获取如下数据框?

我还可以指定仅对 QuestionQ1Q3 的记录使用 answer_sort_order 字典

【问题讨论】:

  • df.iloc[np.argsort(df['Answer'].map(answer_sort_order))]

标签: python python-3.x pandas dataframe data-manipulation


【解决方案1】:

可以使用sort_valueskey参数:

out = df.sort_values('Answer', key=pd.Series(answer_sort_order).reindex)

或:

out = df.sort_values('Answer', key=lambda x: x.map(answer_sort_order))

输出:

  Question          Answer
2       Q1       $1 to $49
4       Q1     $50 to $100
3       Q1    $100 to $200
5       Q3  More than 5000
6       Q3  Less than 5000
0       Q2             Yes
1       Q2              No
7       Q3      Don't know

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多