将Pandas数据框转换为字典

时间:2018-10-13 21:47:57

标签: python pandas dictionary dataframe

我有一个熊猫的日期框架:

+-----------+-------+---------+
| kpi_name  | coeff | measure |
+-----------+-------+---------+
| messi     | 2     | DoD     |
| ronaldo   | 1.5   | MTD     |
| del_piero | 2     | MTD     |
+-----------+-------+---------+

我需要将其转换为字典:

{'MTD':[{'KPI':'ronaldo', 'measure':'1.5'}, {'KPI:':'messi', 'measure':'2'],
 'DoD':['KPI':'messi', 'measure':'1.4']}

我正在尝试:

a = df.groupby('measure').apply(lambda x: x.to_dict('list')).to_dict() 

我的输出:

{'MTD': {'kpi_name': ['ronaldo', 'del_piero'], 'coeff': [1.5, 2.0], 'measure': ['MTD', 'MTD']}, 'DoD': {'kpi_name': ['messi'], 'coeff': [2.0], 'measure': ['DoD']}}

很多帮助!

2 个答案:

答案 0 :(得分:1)

请查看slicing dataframestranspose T,以备将来参考。

给出一个数据框

df = pd.DataFrame({'KPI':['messi', 'ronaldo', 'del_piero'],\
                   'coeff':[2, 1.5, 2], \
                   'measure':['DoD', 'MTD', 'MTD']})

您可以使用以下lambda函数

df.groupby('measure').apply(lambda x: list(x[['KPI','coeff']].T.to_dict().values())).to_dict()

实现预期的输出

{'DoD': [{'KPI': 'messi', 'coeff': 2.0}],
 'MTD': [{'KPI': 'ronaldo', 'coeff': 1.5}, {'KPI': 'del_piero', 'coeff': 2.0}]}

答案 1 :(得分:1)

GroupBy使用字典理解:

df = pd.DataFrame({'kpi_name': ['messi', 'ronaldo', 'del_piero'],
                   'coeff': [2, 1.5, 2],
                   'measure': ['DoD', 'MTD', 'MTD']})

res = {k: grp.to_dict(orient='records') for k, grp in df.groupby('measure')}

print(res)

{'DoD': [{'kpi_name': 'messi', 'coeff': 2.0, 'measure': 'DoD'}],
 'MTD': [{'kpi_name': 'ronaldo', 'coeff': 1.5, 'measure': 'MTD'},
         {'kpi_name': 'del_piero', 'coeff': 2.0, 'measure': 'MTD'}]}