Python 将数据帧转换为对象字典
需要按文件编号对行进行分组,文件编号将用作字典键,并将操作ID和操作注释作为对象 数据帧Python 将数据帧转换为对象字典,python,pandas,numpy,Python,Pandas,Numpy,需要按文件编号对行进行分组,文件编号将用作字典键,并将操作ID和操作注释作为对象 数据帧 **File_Number** **Action_ID** **Action_Note** 0 12 Call Josh 1 15 Text Emily 1 16 Email Guy 2
**File_Number** **Action_ID** **Action_Note**
0 12 Call Josh
1 15 Text Emily
1 16 Email Guy
2 19 Visit Hannah
2 20 Call Ryan
预期产出
{
0: [Action_ID: 12, Action_Note: Call Josh ],
1: [Action_ID: 15, Action_Note: Text Emily], [Action_ID: 16, Action_Note: Email Guy],
2: [Action_ID: 19, Action_Note: Visit Hannah], [Action_ID: 20, Action_Note: Call Ryan],
}
您可以执行两次以下操作:
(df.drop(['File_Number'], axis=1)
.groupby(df['File_Number']).apply(lambda x: x.to_dict('records'))
.to_dict()
)
输出:
{0: [{'Action_ID': 12, 'Action_Note': 'Call Josh'}],
1: [{'Action_ID': 15, 'Action_Note': 'Text Emily'},
{'Action_ID': 16, 'Action_Note': 'Email Guy'}],
2: [{'Action_ID': 19, 'Action_Note': 'Visit Hannah'},
{'Action_ID': 20, 'Action_Note': 'Call Ryan'}]}
您可以执行两次以下操作:
(df.drop(['File_Number'], axis=1)
.groupby(df['File_Number']).apply(lambda x: x.to_dict('records'))
.to_dict()
)
输出:
{0: [{'Action_ID': 12, 'Action_Note': 'Call Josh'}],
1: [{'Action_ID': 15, 'Action_Note': 'Text Emily'},
{'Action_ID': 16, 'Action_Note': 'Email Guy'}],
2: [{'Action_ID': 19, 'Action_Note': 'Visit Hannah'},
{'Action_ID': 20, 'Action_Note': 'Call Ryan'}]}
正是我需要的。非常感谢你!正是我需要的。非常感谢你!