【问题标题】:Stop Pandas from sorting columns阻止 Pandas 对列进行排序
【发布时间】:2020-09-12 16:29:48
【问题描述】:

我正在尝试生成报告,然后运行以下代码


    import pandas as pd

    df = pd.read_excel("proposals2020.xlsx", sheet_name="Proposals")

    country_probability = df.groupby(["Country", "Probability"]).count()
    country_probability = country_probability.unstack()
    country_probability = country_probability.fillna("0")
    country_probability = country_probability.drop(country_probability.columns[4:], axis=1)
    country_probability = country_probability.drop(country_probability.columns[0], axis=1)
    country_probability = country_probability.astype(int)

    print(country_probability)

我得到以下结果:

             Quote Number           
Probability          High Low Medium
Country                             
Algeria                 3   1      9
Bahrain                 4   3      2
Egypt                   2   0      3
Iraq                    3   0      8
Jordan                  0   1      1
Lebanon                 0   1      0
Libya                   1   0      0
Morocco                 0   0      2
Pakistan                3  10     11
Qatar                   0   1      1
Saudi Arabia           16   8     19
Tunisia                 2   5      0
USA                     0   1      0

我的问题是如何阻止熊猫按字母顺序对这些列进行排序并保持高、中、低顺序...

【问题讨论】:

  • 试试 df.sort_values(['High', 'Medium', 'Low'])
  • Groupby 有一个变量 sort,默认设置为 True,你可以通过 sort = False
  • 谢谢 Vaishali.. 对代码进行了一些调整..

标签: python pandas multi-index columnsorting


【解决方案1】:

DataFrame.reindex

# if isinstance(df.columns, pd.MultiIndex)
df = df.reindex(['High', 'Medium', 'Low'], axis=1, level=1) 

如果列中没有 MultiIndex:

# if isinstance(df.columns, pd.Index)
df = df.reindex(['High', 'Medium', 'Low'], axis=1)

我们也可以尝试在groupby中传递sort = False

country_probability = df.groupby(["Country", "Probability"], sort=False).count()

【讨论】:

猜你喜欢
  • 2018-04-11
  • 1970-01-01
  • 2017-04-28
  • 2017-05-28
  • 1970-01-01
  • 2016-04-08
  • 2021-04-20
  • 2014-11-29
相关资源
最近更新 更多