如何将字典列表更改为已定义的数据帧格式?

时间:2019-08-13 10:53:25

标签: python pandas pandas-groupby

我有一个字典列表,如下所示,

list_of_dict = [{"mac":"0010403bf0db", "rssi":-42, 
                 "gw_mac":"b827eb36fb0b", "detail":"main_building"}, 
                {"mac":"0010403bf0db", "rssi":-87, 
                 "gw_mac":"d827fc36gc0c", "detail":"main_building"}]

如何将上面的词典列表转换为下面提到的数据框格式?

required_df = mac            detail        b827eb36fb0b      d827fc36gc0c
              0010403bf0db   main_building  -42              -87

1 个答案:

答案 0 :(得分:1)

首先由构造函数创建DataFrame,如果macdetailgw_mac中的值唯一,则可以由DataFrame.set_indexSeries.unstack重塑:

df  = (pd.DataFrame(list_of_dict)
         .set_index(['mac','detail', 'gw_mac'])['rssi']
         .unstack(fill_value=0)
         .reset_index()
         .rename_axis(None, axis=1))
print (df)
            mac         detail  b827eb36fb0b  d827fc36gc0c
0  0010403bf0db  main_building           -42           -87

如果3列中的值不是唯一的,则必须通过DataFrame.pivot_table进行汇总:

df  = (pd.DataFrame(list_of_dict)
         .pivot_table(index=['mac','detail'],columns='gw_mac',values='rssi', aggfunc='mean')
         .reset_index()
         .rename_axis(None, axis=1))
print (df)
            mac         detail  b827eb36fb0b  d827fc36gc0c
0  0010403bf0db  main_building           -42           -87