Pandas技术问题:按列子图绘制DataFrame中的嵌套Series
Got it, let's work through this problem step by step. The core issue here is that your SUPER-COLUMN holds nested Series, and pandas' default plot(subplots=True) won't automatically recognize inner column names or set proper subplot titles. Here's a scalable approach that works regardless of how many inner columns you have or what their names are:
Step 1: Expand Nested Series into a Standard DataFrame
First, we need to convert the column of nested Series into a structured DataFrame where each inner Series' column becomes a top-level column, and each original DataFrame row maps to a row in this new DataFrame.
Example Setup
Let's replicate your scenario with sample data:
import pandas as pd import matplotlib.pyplot as plt # Create nested Series for demonstration series_row1 = pd.Series([1, 2, 3], index=["a", "b", "c"]) series_row2 = pd.Series([4, 5, 6], index=["a", "b", "c"]) df = pd.DataFrame({"SUPER-COLUMN": [series_row1, series_row2]})
Expand the Nested Column
Extract the inner Series and convert them into a clean DataFrame:
# Convert nested Series into a standard DataFrame expanded_df = pd.DataFrame(df["SUPER-COLUMN"].tolist(), index=df.index)
This gives us a DataFrame where columns are the inner Series' labels (like a, b, c) and rows match the original DataFrame's rows.
Step 2: Plot with Auto-Generated Subplot Titles
Now use subplots=True to create individual subplots for each column, then loop through the subplots to set titles based on the column names:
# Generate subplots and plot each column axes = expanded_df.plot( subplots=True, figsize=(8, 4 * len(expanded_df.columns)), # Scale height to fit all subplots sharex=True, # Optional: Keep x-axis consistent across subplots marker="o" # Optional: Add markers for better readability ) # Assign titles to each subplot (matches inner column names) for ax, column_name in zip(axes, expanded_df.columns): ax.set_title(f"Subplot for Column: {column_name}") # Adjust layout to avoid title overlap plt.tight_layout() plt.show()
Handling Inconsistent Inner Series Indices
If your nested Series don't share the same indices (e.g., one has a, b and another has b, c), use pd.concat to merge them properly (filling gaps with NaN):
# For cases where inner Series have inconsistent indices expanded_df = pd.concat(df["SUPER-COLUMN"].tolist(), axis=1).T expanded_df.index = df.index
Then follow the same plotting steps above — the code will still automatically generate subplots for every unique inner column name.
内容的提问来源于stack exchange,提问作者marcorossi

