【发布时间】: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']})
我想按Question 和Answer 列对数据框进行排序。我创建了一个自定义字典,以便在按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}
如何使用它来获取如下数据框?
我还可以指定仅对 Question 为 Q1 和 Q3 的记录使用 answer_sort_order 字典
【问题讨论】:
-
df.iloc[np.argsort(df['Answer'].map(answer_sort_order))]
标签: python python-3.x pandas dataframe data-manipulation