Mahamutha M
Mahamutha M

Reputation: 1287

How to extract the keys and values of a dictionary as a separate column in a data frame?

I have two data frame which is like,

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}  

I need to extract the keys of "gw_mac_rssi" as "gw_mac" and values of "gw_mac_rssi" as "rssi" which should be

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]

I have tried with,

df['gw_mac'] = list(df['gw_mac_rssi'].keys())

whereas unable to get the required data frame.

Upvotes: 1

Views: 38

Answers (1)

jezrael
jezrael

Reputation: 862511

Use Series.apply for process each value separately:

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

Alternative:

f = lambda x: pd.Series([list(x.keys()), list(x.values())])
df[['gw_mac','rssi']] = df['gw_mac_rssi'].apply(f)

Upvotes: 1

Related Questions