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

如何基于含多值列的DataFrame按ID构建箱线图?

How to Create Boxplots for Costs by ID

Got it, let's walk through how to make boxplots for each ID using their Costs data. Here's a straightforward, reproducible approach with pandas and seaborn (the standard tools for this kind of task):

Step 1: Preprocess the Data into Long Format

First, we need to convert the comma-separated string values in the Costs column into individual numeric entries. Boxplot tools work best with long-format data (one row per data point), so we'll "explode" the list values into separate rows.

import pandas as pd

# Load your data (replace this with pd.read_csv("your_file.csv") if using a CSV)
raw_data = {
    "ID": ["tim", "ryan", "bob"],
    "Costs": ["1, 2, 3, 4, 5, 6, 7, 8", "8, 7, 6, 5, 4, 3, 2, 1", "1, 3, 5, 7, 9, 11, 13, 15"]
}
df = pd.DataFrame(raw_data)

# Convert Costs from string to list of integers
df["Costs"] = df["Costs"].str.split(", ").apply(lambda x: [int(val) for val in x])

# Explode the list into individual rows (long format)
df_long = df.explode("Costs", ignore_index=True)

# Ensure Costs is numeric (explode might leave it as object type)
df_long["Costs"] = df_long["Costs"].astype(int)

Step 2: Generate the Boxplot

With the data in long format, we can use seaborn's boxplot function to automatically group data by ID and plot the distribution of Costs.

import seaborn as sns
import matplotlib.pyplot as plt

# Set a clean plot style
sns.set_style("whitegrid")

# Create the plot
plt.figure(figsize=(8, 5))
sns.boxplot(x="ID", y="Costs", data=df_long)

# Add labels and title for clarity
plt.title("Cost Distribution by ID", fontsize=14)
plt.xlabel("User ID", fontsize=12)
plt.ylabel("Cost Value", fontsize=12)

# Show the plot
plt.show()

Key Notes

  • Long format is critical: Most visualization libraries expect one observation per row. Exploding the list avoids having to manually calculate quartiles/medians for each ID.
  • This approach works even if your original data has varying lengths of Cost lists (though in your example, all are 8 entries).
  • You can customize the plot further (colors, outliers, etc.) using seaborn's built-in parameters.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:48