You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame中字典列的键和值提取为独立列?

Fixing Dictionary Column Expansion in Pandas 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:

buildinglevelsitemac_locationgw_macrssi
2b2nd-floorcrystal-lawnlab['ac233fc01403','ac233fc015f6','ac233fc02eaa'][-32.0,-45.5,-82]
2b2nd-floorcrystal-lawnconference['ac233fc01403','ac233fc015f6','ac233fc02eaa'][-82, -45.5, -82]

内容的提问来源于stack exchange,提问作者Mahamutha M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:06:29