如何将零件编号列表转换为以宽/长为行列的二维网格(Pandas)
Let me break down where your current code is going off track, and show you a straightforward way to build the grid you need.
The Problem with Your Current Approach
Your initial code tries to manually collect columns/rows and build a list of triples, but then the numpy array slicing step is misaligned with your data structure—your li contains individual part entries, not a pre-formatted table where the first row is column names and first column is row labels. That's why the DataFrame isn't turning out as expected. The extra data_dict/grid_data code also seems disconnected from your main goal here.
The Correct Solution Using Pandas Pivot
Pandas has built-in tools (pivot or pivot_table) that are perfect for reshaping your part data into the grid layout you want. Here's a step-by-step implementation:
1. First, Let's Define Sample Data (to match your example)
# Simulate your part_list structure class Part: def __init__(self, part_number, width, length): self.part_number = part_number self.width = width self.length = length part_list = [ Part("no1", "width1", "len1"), Part("no2", "width2", "len1"), Part("no3", "width1", "len2"), Part("no4", "width2", "len2"), Part("no5", "width3", "len2"), Part("no6", "width1", "len3"), Part("no7", "width2", "len3"), Part("no8", "width3", "len3"), Part("no9", "width4", "len3"), ]
2. Convert Your Part List to a Raw DataFrame
First, we'll translate your part_list into a simple Pandas DataFrame where each row represents one part:
import pandas as pd # Create a raw DataFrame from your part list df_raw = pd.DataFrame([ { "width": part.width, "length": part.length, "part_number": part.part_number } for part in part_list ])
3. Reshape into the Width-Length Grid
Use pivot to rearrange the data so:
- Rows are your
lengthvalues - Columns are your
widthvalues - Cells contain the corresponding
part_number(empty if no part exists for that combination)
# Build the grid using pivot df_grid = df_raw.pivot( index="length", # Use length values as row labels columns="width", # Use width values as column labels values="part_number" # Fill cells with part numbers ) # Optional: Sort rows and columns to match your example's order df_grid = df_grid.reindex(sorted(df_grid.index)) # Sort length rows df_grid = df_grid[sorted(df_grid.columns)] # Sort width columns # Replace NaN (empty cells) with blank strings if preferred df_grid = df_grid.fillna("")
4. The Final Output
Running this will give you exactly the grid you want:
width width1 width2 width3 width4 length len1 no1 no2 len2 no3 no4 no5 len3 no6 no7 no8 no9
Key Notes
- No need to manually collect columns/rows with loops—Pandas handles extracting unique values from the raw data automatically.
- The
pivotmethod is ideal here because each (width, length) combination has at most one part number. If you ever have multiple parts per combination, usepivot_tableinstead with an aggregation function (likefirst()).
内容的提问来源于stack exchange,提问作者wmfox3

