Python 3.x 如何将字典中的键和值提取为数据帧中的单独列?
我有两个数据框,就像Python 3.x 如何将字典中的键和值提取为数据帧中的单独列?,python-3.x,pandas,dictionary,Python 3.x,Pandas,Dictionary,我有两个数据框,就像 df: building level site mac_location gw_mac_rssi 0 2b 2nd-floor crystal-lawn lab {'ac233fc01403': -32.0, 'ac233fc015f6': -45.5, 'ac233fc02eaa': -82} 1 2b 2nd-floor crystal-lawn conference
df:
building level site mac_location gw_mac_rssi
0 2b 2nd-floor crystal-lawn lab {'ac233fc01403': -32.0, 'ac233fc015f6': -45.5, 'ac233fc02eaa': -82}
1 2b 2nd-floor crystal-lawn conference {'ac233fc01403': -82, 'ac233fc015f6': -45.5, 'ac233fc02eaa': -82}
我需要将“gw_mac_rssi”的键提取为“gw_mac”,将“gw_mac_rssi”的值提取为“rssi”,这应该是
required_df:
building level site mac_location gw_mac rssi
0 2b 2nd-floor crystal-lawn lab ['ac233fc01403','ac233fc015f6','ac233fc02eaa'] [-32.0,-45.5,-82]
1 2b 2nd-floor crystal-lawn conference ['ac233fc01403','ac233fc015f6','ac233fc02eaa'] [-82, -45.5, -82]
我试过了
df['gw_mac'] = list(df['gw_mac_rssi'].keys())
而无法获取所需的数据框。分别用于处理每个值:
df['gw_mac'] = df['gw_mac_rssi'].apply(lambda x: list(x.keys()))
df['rssi'] = df['gw_mac_rssi'].apply(lambda x: list(x.values()))
备选方案:
f = lambda x: pd.Series([list(x.keys()), list(x.values())])
df[['gw_mac','rssi']] = df['gw_mac_rssi'].apply(f)