如何实现从JSON格式到表格格式的Feature Mapping(Pop)?
How to Expand JSON-like Dictionaries into Table Columns (Feature Mapping)
Got it, let's solve this problem where you need to unpack the dictionaries in the var_map column into individual feature columns. Using Python's Pandas library is the most straightforward way to handle this—here's a step-by-step solution:
Step 1: Set Up Your Data
First, let's recreate your original dataset in Pandas (adjust this if your data comes from a file like CSV/JSON):
import pandas as pd # Original dataset data = { 'id': [7068, 7116, 7154], 'var_map': [ {'feature_1': 2.0, 'feature_2': 4.0, 'feature_3': 8.0, 'feature_4': 8.0}, {'feature_1': '2', 'feature_2': 5.0, 'feature_3': 7.0}, {'feature_1': 1.0, 'feature_2': 8.0, 'feature_3': 17.0} ] } df = pd.DataFrame(data)
Step 2: Expand the Dictionary Column
We'll use pd.Series to convert each dictionary in var_map into a row of features, then concatenate this with the original id column:
# Unpack the var_map dictionaries into separate columns expanded_features = df['var_map'].apply(pd.Series) # Combine the original id column with the expanded features result_df = pd.concat([df['id'], expanded_features], axis=1) # Optional: Replace NaN values with empty strings to match your desired output result_df = result_df.fillna('')
Step 3: View the Result
Running the code above will give you exactly the table format you want:
id feature_1 feature_2 feature_3 feature_4 feature_5 0 7068 2.0 4.0 8.0 8.0 1 7116 2 5.0 7.0 2 7154 1.0 8.0 17.0
Key Notes:
- Pandas automatically handles missing keys (like
feature_4/feature_5in rows 1 and 2) by filling them withNaN—we usefillna('')to convert those to empty strings as shown in your example. - If your data is coming from a CSV where
var_mapis stored as a string (not a Python dictionary), you'll need to first parse it usingast.literal_eval():import ast df['var_map'] = df['var_map'].apply(ast.literal_eval)
内容的提问来源于stack exchange,提问作者Nabih Bawazir
相关产品推荐
相关产品推荐

