【问题标题】:How to extract the keys and values of a dictionary as a separate column in a data frame?如何将字典的键和值提取为数据框中的单独列?
【发布时间】:2019-08-19 08:18:47
【问题描述】:

我有两个数据框,就像,

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())

而无法获得所需的数据帧。

【问题讨论】:

    标签: python-3.x pandas dictionary


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 2018-01-31
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2021-08-24
      相关资源
      最近更新 更多