您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

按月份名称对pandas的数据框系列进行排序?

按月份名称对pandas的数据框系列进行排序?

感谢@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有一个有效的示例,可按月索引对按熊猫系列排列的分类索引进行排序

其他 2022/1/1 18:29:52 有539人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶