Pandas:拆分列表为行及移除列表索引值问题
Got it, let's break this down step by step to fix your Pandas workflow. Here's exactly how you can clean those indexed values and split list elements into individual rows:
Step 1: Clean the indexed values from each list
First, we'll write a simple helper function to strip out those leading numbers (like 6 from 6 X) using regex. This will leave only the actual value you care about without the index clutter.
Step 2: Build your initial DataFrame
We’ll take your cleaned lists and create a DataFrame where each row contains lists of values (matching your current setup of concatenating columns with list elements).
Step 3: Explode lists into individual rows
Pandas' explode() method is perfect for this—it takes each element in a list column and turns it into its own row, while keeping corresponding values in other columns perfectly aligned.
Full Working Code Example
import pandas as pd import re # Example input lists (matches your indexed value format) id_list = [["1 A", "2 B"], ["3 C"]] version_list = [["4 V1", "5 V2"], ["6 V3"]] phases_list = [["7 P1", "8 P2"], ["9 P3"]] # Helper function to remove leading index numbers and spaces def clean_indexed_value(item): # Regex matches one or more digits at the start, followed by a space, then replaces with empty string return re.sub(r'^\d+\s+', '', item) # Clean every element in all three lists cleaned_ids = [[clean_indexed_value(sub_item) for sub_item in row] for row in id_list] cleaned_versions = [[clean_indexed_value(sub_item) for sub_item in row] for row in version_list] cleaned_phases = [[clean_indexed_value(sub_item) for sub_item in row] for row in phases_list] # Create the initial DataFrame with list columns df = pd.DataFrame({ "ID": cleaned_ids, "Version": cleaned_versions, "Phases": cleaned_phases }) # Explode all list columns into individual rows (resets index for clean output) final_df = df.explode(["ID", "Version", "Phases"], ignore_index=True) # Export to Excel (no index column in the output) final_df.to_excel("cleaned_output.xlsx", index=False)
If your list elements are comma-separated strings instead of lists
If your original lists look like id_list = ["1 A, 2 B", "3 C"] (where each item is a single string with multiple indexed values), just adjust the cleaning function to split and clean in one go:
def clean_and_split_values(item): # Split comma-separated values, strip whitespace, then clean each part parts = [p.strip() for p in item.split(",")] return [re.sub(r'^\d+\s+', '', p) for p in parts] # Apply to your lists cleaned_ids = [clean_and_split_values(row) for row in id_list] # Repeat for version_list and phases_list, then proceed with the explode step as above
This will give you an Excel file where every value is in its own row, with no leftover index numbers.
内容的提问来源于stack exchange,提问作者Darshan Malu

