You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于DataFrame绘制月份累计值条形图的技术实现需求

Got it, let's walk through how to build this bar chart exactly as you need it. We'll split this into two main parts: cleaning and aggregating your data, then plotting the final chart.

Solution: Aggregated Monthly Value Bar Chart

Step 1: Clean & Transform the Data

First, we need to fix data types, merge duplicate month values, and convert numeric months to properly ordered English names.

import pandas as pd
import matplotlib.pyplot as plt

# Your original dataset
df = pd.DataFrame( { "Months": [1, 2, 2, 4], "Value": ["1000", "2000", "1500", "3200"], } )

# 1. Convert Value from string to integer (we can't sum strings!)
df["Value"] = df["Value"].astype(int)

# 2. Map numeric months to English names, then enforce correct order
month_map = {
    1: "January",
    2: "February",
    3: "March",
    4: "April"
    # Add more months here if your dataset expands later
}
df["Month_Name"] = df["Months"].map(month_map)

# Use ordered categories to avoid alphabetical sorting (no more April before February!)
df["Month_Name"] = pd.Categorical(
    df["Month_Name"],
    categories=["January", "February", "March", "April"],
    ordered=True
)

# 3. Sum values for duplicate months
aggregated_df = df.groupby("Month_Name", observed=True)["Value"].sum().reset_index()

Step 2: Plot the Bar Chart

Now we can build the chart with our cleaned, aggregated data:

# Set up the plot
plt.figure(figsize=(8, 5))
bars = plt.bar(aggregated_df["Month_Name"], aggregated_df["Value"], color="#1f77b4")

# Add value labels on top of each bar for clarity
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height:,}',  # Format numbers with commas
             ha='center', va='bottom')

# Customize labels and title
plt.xlabel("Months")
plt.ylabel("Total Value")
plt.title("Monthly Aggregated Value")
plt.tight_layout()  # Prevent label cutoff

# Show the finished chart
plt.show()

Quick Key Notes:

  • The pd.Categorical step is critical—without it, pandas would sort month names alphabetically, which breaks the chronological order.
  • observed=True in the groupby ensures we only show months that exist in your data (so March won't appear since it's missing from your original dataset).
  • Converting the Value column to integers is non-negotiable; string values can't be summed correctly.

内容的提问来源于stack exchange,提问作者TRM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:09:12