我有一个字典列表,如下所示,
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
答案 0 :(得分:1)
首先由构造函数创建DataFrame
,如果mac
,detail
和gw_mac
中的值唯一,则可以由DataFrame.set_index
和Series.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