根据Pandas数据框架的列值创建嵌套字典?



我有一个数据框架

df1 = pd.DataFrame(data={'col1': [21, 44, 28, 32, 20, 39, 42], 
'col2': ['<1', '>2', '>2', '>3', '<1', '>2', '>4'], 
'col3': ['yes', 'yes', 'no', 'no', 'yes', 'no', 'yes'], 
'col4': [1, 1, 0, 0, 1, 0, 1], 
'Group': [0, 2, 1, 1, 0, 1, 2] })
col1 col2 col3  col4  Group
0    21   <1  yes     1      0
1    44   >2  yes     1      2
2    28   >2   no     0      1
3    32   >3   no     0      1
4    20   <1  yes     1      0
5    39   >2   no     0      1
6    42   >4  yes     1      2

基于'Group'列值0,1,2,我需要创建一个嵌套的字典,如

{0: {'col1': {'mean': 20.5, 'sd': 0.5},
'col2': ['<1'],
'col3': ['yes'],
'col4': {'mean': 1, 'sd': 0}},
1: {'col1': {'mean': 33, 'sd': 4.54},
'col2': ['>2', '>3'],
'col3': ['no'],
'col4': {'mean': 0, 'sd': 0}},
2: {'col1': {'mean': 43, 'sd': 1},
'col2': ['>2', '>4'],
'col3': ['yes'],
'col4': {'mean': 1, 'sd': 0}}}

col1和col4是数字,col2和col3是字符串

对于组0:

'col1':值20,21的均值和标准差

'col2':只有'<1'

'col3':只有'yes'

'col4':值1,1的均值和标准差

对于组1:

'col1':值28,32,39的均值和标准差

'col2':包含'>2'和'>3'

'col3':只有'no'

'col4': 0,0,0的平均值和平均值

对于组2:

'col1':值42,44的平均值和标准值

'col2':包含'>2'和'>4'

'col3':只有'yes'

'col4':值1,1的均值和标准差

df1.groupby('Group').agg(lambda x: x.unique().tolist() if x.dtype =='object' 
else {'mean':x.mean(), 'std':x.std(ddof=0)}).T.to_dict('index')
Out[396]: 
{0: {'col1': {'mean': 20.5, 'std': 0.5},
'col2': ['<1'],
'col3': ['yes'],
'col4': {'mean': 1.0, 'std': 0.0}},
1: {'col1': {'mean': 33.0, 'std': 4.546060565661952},
'col2': ['>2', '>3'],
'col3': ['no'],
'col4': {'mean': 0.0, 'std': 0.0}},
2: {'col1': {'mean': 43.0, 'std': 1.0},
'col2': ['>2', '>4'],
'col3': ['yes'],
'col4': {'mean': 1.0, 'std': 0.0}}}

最新更新