感谢@Brad Solomon提供了一种更快的大写字符串方式!
@Brad Solomon的答案使用pd.categorical
应该比我的答案节省更多资源。他展示了如何为您的分类数据分配顺序。你不应该错过它:P
或者,您可以使用。
df = pd.DataFrame([["dec", 12], ["jan", 40], ["mar", 11], ["aug", 21],
["aug", 11], ["jan", 11], ["jan", 1]],
columns=["Month", "Price"])
# Preprocessing: capitalize `jan`, `dec` to `Jan` and `Dec`
df["Month"] = df["Month"].str.capitalize()
# Now the dataset should look like
# Month Price
# -----------
# Dec XX
# Jan XX
# Apr XX
# make it a datetime so that we can sort it:
# use %b because the data use the abbriviation of month
df["Month"] = pd.to_datetime(df.Month, format='%b', errors='coerce').dt.month
df = df.sort_values(by="Month")
total = (df.groupby(df['Month"])['Price'].mean())
# total
Month
1 17.333333
3 11.000000
8 16.000000
12 12.000000
groupby
默认情况下会为您排序组密钥。请注意,在和中使用相同的键进行排序和分组df = df.sort_values(by=SAME_KEY)
,total = (df.groupby(df[SAME_KEY])['Price'].mean()).
否则,可能会发生意外行为。 一种更有效的计算方法是先计算均值,然后按月进行排序。这样,您只需要排序12个项目,而不是整个项目df
。如果不需要df
分类,它将减少计算成本。
对于已经拥有 ,想知道如何使其分类,请看一下熊猫。CategoricalIndex
@jezrael有一个有效的示例,可按月索引对按熊猫系列排列的分类索引进行排序