按特定规则将两个嵌套列表映射生成DataFrame的技术需求
Got it, let's tackle this problem where we need to map two nested lists into a structured DataFrame, filling missing values with 0 (or null if preferred). Here's a straightforward approach using pandas:
Step 1: Import pandas and define your lists
First, we'll start by importing the pandas library and declaring your input lists:
import pandas as pd list1 = [['a','b','c'],['a','d'],['a','f','c']] list2 = [['S1','S2','S3'],['S1','S3'],['S1','S2','S3']]
Step 2: Define target columns
We know the columns we need are S1, S2, S3 (we can also extract them dynamically from list2 if needed, but hardcoding here keeps it simple for your use case):
target_columns = ['S1', 'S2', 'S3']
Step 3: Build row dictionaries
We'll pair each sublist from list1 with its corresponding sublist from list2, create a dictionary mapping each S* key to its value from list1, then fill in any missing columns with 0 (or null):
rows = [] for l1_items, l2_keys in zip(list1, list2): # Create initial mapping from S keys to list1 values row_data = dict(zip(l2_keys, l1_items)) # Fill missing columns with 0 (replace with pd.NA for nulls) for col in target_columns: if col not in row_data: row_data[col] = 0 rows.append(row_data)
Step 4: Convert to DataFrame
Finally, we'll turn our list of dictionaries into a pandas DataFrame, ensuring columns are in the order we want:
df = pd.DataFrame(rows, columns=target_columns) print(df)
Output
Running this code will give you exactly the structure you're looking for:
S1 S2 S3 0 a b c 1 a 0 d 2 a f c
If you prefer null instead of 0, just replace row_data[col] = 0 with row_data[col] = pd.NA in the loop. That will give you missing values marked as pandas' native null type.
内容的提问来源于stack exchange,提问作者Akshay Sachdeva

