问题描述
用Pythonic/pandas方式对pandas列中的级别"进行排序,以在条形图中给出条形的特定顺序.
What is the Pythonic/pandas way of sorting 'levels' within a column in pandas to give a specific ordering of bars in bar plot.
例如,给定:
import pandas as pd
df = pd.DataFrame({
'group': ['a', 'a', 'a', 'a', 'a', 'a', 'a',
'b', 'b', 'b', 'b', 'b', 'b', 'b'],
'day': ['Mon', 'Tues', 'Fri', 'Thurs', 'Sat', 'Sun', 'Weds',
'Fri', 'Sun', 'Thurs', 'Sat', 'Weds', 'Mon', 'Tues'],
'amount': [1, 2, 4, 2, 1, 1, 2, 4, 5, 3, 4, 2, 1, 3]})
dfx = df.groupby(['group'])
dfx.plot(kind='bar', x='day')
我可以生成以下对图:
条形图的顺序遵循行顺序.
The order of the bars follows the row order.
重新排序数据的最佳方法是什么,以使条形图具有按周一至周日排序的条形图?
What's the best way of reordering the data so that the bar charts have bars ordered Mon-Sun?
更新:此垃圾解决方案有效-但它使用额外的排序列的方式远非优雅:
UPDATE: this rubbish solution works - but it's far from elegant in the way it uses an extra sorting column:
df2 = pd.DataFrame({
'day': ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'],
'num': [0, 1, 2, 3, 4, 5, 6]})
df = pd.merge(df, df2, on='day')
df = df.sort_values('num')
dfx = df.groupby(['group'])
dfx.plot(kind='bar', x='day')
进一步通用化:
是否有一种解决方案,还可以固定闪避"条形图中的条形顺序:
Is there a solution that also fixes the order of bars in a 'dodged' bar plot:
df.pivot('day', 'group', 'amount').plot(kind='bar')
推荐答案
您将必须提供映射以指定如何订购日期名称. (如果将它们存储为正确的日期,则还有其他方法可以做到这一点.)
You'll have to provide a mapping to specify how to order the day names. (If they were stored as proper dates, there would be other ways to do this.)
已更新:
构建密钥.您可以显式地编写字典,也可以使用诸如dict理解之类的聪明方法.
Build the key. You could write out a dictionary explicitly or use something clever like this dict comprehension.
weekdays = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun']
mapping = {day: i for i, day in enumerate(weekdays)}
key = df['day'].map(mapping)
排序很简单:
df.iloc[key.argsort()]
这篇关于在pandas/matplotlib条形图中对条形排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!