如何用Pandas中列值作为嵌套字典的键新增列?
How to Map a Nested Dictionary to a New Pandas DataFrame Column
Let’s start with sample data matching your structure to make this concrete:
import pandas as pd # Your nested dictionary dict1 = { 'key1': {'key2': 'value12', 'key3': 'value13'}, 'key4': {'key5': 'value45', 'key6': 'value46'} } # Your DataFrame with A and B columns df = pd.DataFrame({ 'A': ['key1', 'key4', 'key1'], 'B': ['key2', 'key5', 'key3'] })
Why Your Previous Attempts Failed
dict1[df['A']][df['C']]: Dictionaries can’t be indexed with a pandas Series (which is whatdf['A']is)—they require single scalar keys, so this throws an error.- The
applycall withlambda x,y: When usingapplyon a DataFrame, each row is passed as a single argument to the lambda, not two separate values. Your lambda expects two inputs but only gets one, leading to a mismatch.
Efficient, Loop-Free Solutions
Method 1: Use apply with axis=1 (Simple & Readable)
This approach avoids explicit loops like itertuples() or iterrows() and is easy to understand. We pass each row to a lambda that performs the nested lookup:
df['C'] = df.apply(lambda row: dict1[row['A']][row['B']], axis=1)
Method 2: Flatten the Dict for Vectorized Lookup (Faster for Large Data)
For big DataFrames, a fully vectorized approach will perform better. First flatten your nested dict into a multi-index Series, then map the (A,B) tuples from your DataFrame to it:
# Flatten the nested dict into a Series with (outer_key, inner_key) as index flat_lookup = pd.Series({(outer, inner): val for outer, inner_dict in dict1.items() for inner, val in inner_dict.items()}) # Map the (A,B) pairs from the DataFrame to the flattened Series df['C'] = df.set_index(['A', 'B']).index.map(flat_lookup.get) df = df.reset_index(drop=True) # Restore original index if needed
Method 3: Two-Step map (Clearer Breakdown)
You can split the lookup into two steps for better readability: first map column A to get the inner dictionaries, then extract values using column B:
# Step 1: Retrieve the inner dict for each row using column A df['inner_dict'] = df['A'].map(dict1) # Step 2: Look up the value from the inner dict using column B df['C'] = df.apply(lambda row: row['inner_dict'][row['B']], axis=1) # Clean up the temporary column df.drop('inner_dict', axis=1, inplace=True)
Final Result
After applying any of these methods, your DataFrame will have the desired C column:
| A | B | C | |
|---|---|---|---|
| 0 | key1 | key2 | value12 |
| 1 | key4 | key5 | value45 |
| 2 | key1 | key3 | value13 |
内容的提问来源于stack exchange,提问作者formicaman
相关产品推荐
相关产品推荐

