【问题标题】:Pandas pivot_table, sort values by columnsPandas pivot_table,按列对值进行排序
【发布时间】:2017-04-28 10:14:45
【问题描述】:

我是 Pandas 的新用户,我喜欢它!

我正在尝试在 Pandas 中创建数据透视表。一旦我以我想要的方式拥有数据透视表,我想按列对值进行排名。

我附上了一张 Excel 中的图片,因为它更容易以表格格式查看我想要实现的目标。 Link to image

我已经通过 stackoverflow 进行了搜索,但无法找到答案。我尝试使用 .sort() 但这不起作用。任何帮助将不胜感激。

提前致谢

【问题讨论】:

标签: python pandas indexing pivot-table


【解决方案1】:

这应该可以满足您的需求:

In [1]: df = pd.DataFrame.from_dict([{'Country': 'A', 'Year':2012, 'Value': 20, 'Volume': 1}, {'Country': 'B', 'Year':2012, 'Value': 100, 'Volume': 2}, {'Country': 'C', 'Year':2013, 'Value': 40, 'Volume': 4}])

In [2]: df_pivot = pd.pivot_table(df, index=['Country'], columns = ['Year'],values=['Value'], fill_value=0)

In [3]: df_pivot
Out [4]:
    Value     
Year     2012 2013
Country           
A          20    0
B         100    0
C           0   40

In [5]: df = df_pivot.reindex(df_pivot['Value'].sort_values(by=2012, ascending=False).index)

Out [6]: 
    Value     
Year     2012 2013
Country           
B         100    0
A          20    0
C           0   40

基本上它获取排序值的索引并重新索引初始数据透视表。

【讨论】:

  • 感谢您的帮助!您的代码运行良好。很抱歉没有发布代码本身。下次我会这样做。
  • 如果它适合你,你能接受答案吗?谢谢。
  • 谢谢!只是一个小提示:[5] 中的最后一个命令应该是 df_pivot.reindex,而不是 df
【解决方案2】:

您可以对数据透视表中的多个列进行排序。就我而言,我有邮政编码发生事故的概率和地址发生事故的概率,以降序排序并在热图中显示结果。

pivot = df.pivot_table(index=['postcode'],values=['probability_at_address','probability_at_postcode'],aggfunc='mean').sort_values(by=['probability_at_address','probability_at_postcode'],ascending=False)
fig,ax=plt.subplots(figsize=(10,20))
sns.heatmap(pivot,cmap="Blues",ax=ax)
plt.show()

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 2016-09-14
    • 2020-08-31
    • 1970-01-01
    • 2021-09-02
    • 2020-03-08
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多