如何将字典的键和值提取为数据帧中的单独列?

时间:2019-08-19 08:18:47

标签: 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    {'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())

无法获取所需的数据帧。

1 个答案:

答案 0 :(得分:1)

使用Series.apply分别处理每个值:

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)