python - Groupby 保持组间顺序?以何种方式?

标签 python python-3.x pandas

在回答问题时 Sort a pandas's dataframe series by month name?我们遇到了 groupby 的一些奇怪行为。

df = pd.DataFrame([["dec", 12], ["jan", 40], ["mar", 11], ["aug", 21], ["aug", 11], ["jan", 11], ["jan", 1]], columns=["Month", "Price"])
df["Month_dig"] = pd.to_datetime(df.Month, format='%b', errors='coerce').dt.month
df.sort_values(by="Month_dig", inplace=True)

# Now df looks like
    Month   Price   Month_dig
1   jan     40      1
5   jan     11      1
6   jan     1       1
2   mar     11      3
3   aug     21      8
4   aug     11      8
0   dec     12      12

total = (df.groupby(df['Month'])['Price'].mean())
print(total)
# output
Month
aug    16.000000
dec    12.000000
jan    17.333333
mar    11.000000
Name: Price, dtype: float64

似乎在total中,数据是按字母顺序排序的。虽然 OP 和我都在期待

Month
jan    17.333333
mar    11.000000
aug    16.000000
dec    12.000000
Name: Price, dtype: float64

groupby 背后的机制是什么?我知道它保留了文档中每个组内的顺序,但是是否有关于组间顺序的规则?在我看来,一个非常简单的组顺序应该是 ["jan", "mar", "aug", "dec"] 因为 df 中的数据是以这种方式排序的。

附注从 ["aug", "dec", "jan", "mar"] 来看,这些组名似乎是按字母顺序排序的。
我正在使用 Python 3.6 和 pandas '0.20.3'

最佳答案

pandas.DataFrame.groupby有一个默认为 Truesort 参数。尝试

total = (df.groupby(df['Month'], sort=False)['Price'].mean())

关于python - Groupby 保持组间顺序?以何种方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044542/

相关文章:

python - 类型错误:write() 中不支持类型 <type 'list' >

python - 将一列零添加到 csr_matrix

Python 类设计 : explicit keyword arguments vs. **kwargs 与 @property

python - 在 python 中使用类型提示悬挂缩进的适当缩进级别是多少?

python 3 : __builtins__. 无 : Invalid syntax?

ide - 具有代码完成功能的 python IDE,包括参数对象类型推断

Python Pandas - 缺少必需的依赖项 ['numpy'] 1

python - 如何通过 id 对列进行重采样

python - Plotly Plot surface 3D 不显示

python - 如何在 SWIG 包装 C++ 代码中向目标语言(特别是 Python)添加替代构造函数