将按数据框架汇总的组转换为Dict

时间:2019-02-27 17:18:51

标签: python pandas dictionary

我有一个来自数据抓取过程的以下决定。数据最终存储在数据库中,而我想做的是减少本质上是重复的数据。数据被捕获在comp字典中,然后将其转换为数据帧并转置列和行。

import pandas as pd
import numpy as np

comp={0:{'bedroom':1,'bathroom':1,'price':1225},
      1:{'bedroom':2,'bathroom':2,'price':1385},
      2:{'bedroom':2,'bathroom':2,'price':1625}
      }

frame = pd.DataFrame(comp)
tran_frame  = frame.T
gb = tran_frame.groupby(['bedroom','bathroom'])

gb.agg({'price':{'price_min':np.min,'price_max':np.max}})

然后我按卧室和浴室分组,将价格汇总到最小和最大,我想要得到的是一本看起来像这样的字典

new_comp={0:{'bedroom':1,'bathroom':1,'price_min':1225,'price_max':1225},
          1:{'bedroom':2,'bathroom':2,'price_min':1385,'price_max':1625},
          }

当我将最后一步转换成字典时,我现在得到的是这个

{(1, 1): {('price', 'price_min'): 1225, ('price', 'price_max'): 1225}, (2, 2): {('price', 'price_min'): 1385, ('price', 'price_max'): 1625}}

0 个答案:

没有答案