我有一个df,如下所示
Params Value
teachers 49
students 289
R 3.7
holidays 165
OS 18
Em_from 2020-02-29T20:00:00.000Z
Em_to 2020-03-20T20:00:00.000Z
Em_F 3
Em_C 2
sC_from 2020-03-31T20:00:00.000Z
sC_to 2020-05-29T20:00:00.000Z
sC_F 25
sC_C 31
从上面的df中,我想将其转换为字典的字典,如下所示。
字典:
{'teachers': 49,
'students': 289,
'R': 3.7,
'holidays': 165,
'OS':18,
'Em': {'from': '2020-02-29T20:00:00.000Z', 'to': '2020-03-20T20:00:00.000Z',
'F': 3, 'C': 2},
'sC': {'from': '2020-03-31T20:00:00.000Z', 'to': '2020-05-29T20:00:00.000Z',
'F': 25, 'C': 31}}
用:
s = df['Params'].str.split('_')
m = s.str.len().eq(1)
d1 = df[m].set_index('Params')['Value'].to_dict()
d2 = df[~m].assign(Params=s.str[-1]).agg(tuple, axis=1)\
.groupby(s.str[0]).agg(lambda s: dict(s.tolist())).to_dict()
dct = {**d1, **d2}
结果:
{'Em': {'C': '2',
'F': '3',
'from': '2020-02-29T20:00:00.000Z',
'to': '2020-03-20T20:00:00.000Z'},
'OS': '18',
'R': '3.7',
'holidays': '165',
'sC': {'C': '31',
'F': '25',
'from': '2020-03-31T20:00:00.000Z',
'to': '2020-05-29T20:00:00.000Z'},
'students': '289',
'teachers': '49'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句