如何将DataFrame中字典列的键和值提取为独立列?
Hey there! Let's resolve the issue you're facing when trying to extract keys and values from the dictionary column gw_mac_rssi into separate list columns. The problem with your initial code df['gw_mac'] = list(df['gw_mac_rssi'].keys()) is that it attempts to get keys from the entire Series object instead of each individual dictionary in every row.
Here are two reliable solutions to achieve your desired required_df:
Solution 1: Use apply() for Row-wise Processing
This method iterates over each row's dictionary and extracts keys/values directly:
# Extract dictionary keys into gw_mac column as lists df['gw_mac'] = df['gw_mac_rssi'].apply(lambda x: list(x.keys())) # Extract dictionary values into rssi column as lists df['rssi'] = df['gw_mac_rssi'].apply(lambda x: list(x.values())) # Optional: Remove the original dictionary column if not needed required_df = df.drop(columns=['gw_mac_rssi'])
Solution 2: Use Pandas' str Accessor for Dictionaries
Pandas supports dictionary operations via the str accessor, which can be paired with apply(list) to convert the resulting iterables into lists:
# Extract keys to gw_mac df['gw_mac'] = df['gw_mac_rssi'].str.keys().apply(list) # Extract values to rssi df['rssi'] = df['gw_mac_rssi'].str.values().apply(list) # Clean up to get required_df required_df = df.drop(columns=['gw_mac_rssi'])
Verification
After running either solution, your required_df will match the desired output:
| building | level | site | mac_location | gw_mac | rssi |
|---|---|---|---|---|---|
| 2b | 2nd-floor | crystal-lawn | lab | ['ac233fc01403','ac233fc015f6','ac233fc02eaa'] | [-32.0,-45.5,-82] |
| 2b | 2nd-floor | crystal-lawn | conference | ['ac233fc01403','ac233fc015f6','ac233fc02eaa'] | [-82, -45.5, -82] |
内容的提问来源于stack exchange,提问作者Mahamutha M

