首页 > 解决方案 > Pandas 绑定到左对齐 groupby 之后的第二个索引

问题描述

这是我的代码:

popular_df = purchase_data_df.groupby(["Item ID", "Item Name"])
popular_df.count()

item_count = popular_df["Item Name"].count()
item_price = popular_df["Price"].mean()
total_pur_val = popular_df["Price"].sum()

popular_item_df = pd.DataFrame({"Purchase Count":item_count,
                                "Item Price":item_price,
                                "Total Purchase Value":total_pur_val
                               })
popular_item_df = popular_item_df.sort_values("Total Purchase Value", ascending=False)
popular_item_df["Item Price"] = popular_item_df["Item Price"].map("${:,.2f}".format)
popular_item_df["Total Purchase Value"] = popular_item_df["Total Purchase Value"].map("${:,.2f}".format)

popular_item_df.head()

输出是:

分组输出

我怎样才能左对齐'项目名称'索引,类似于你在 excel 中的做法?

标签: pythonpandasjupyter

解决方案


推荐阅读