有没有办法连接两列并将一行作为新列而不是整列的键值对?



我正在使用pyodbc和pandas从不同机器的数据库中获取数据。我已经编写了用于获取 45 列的结束数据帧的 SQL,然后将其发送给上面的人进行验证。但因此,数据帧看起来很糟糕且杂乱无章。

一些列,例如

0, 'Windows Vista'
'error_info_id', 'error_info_description',
0, 'no error'
'user_status_id', 'user_status_details',
1,'off'
'volume_letter','volume_id','volume_cost','volume_date','volume_end_date'
'C','asd12edsdasd',100,'2019-09-09 16:45:46.007','2022-09-09 16:45:46.007

可以合并成一个喜欢

operating system
{'Id': 0, 'name': 'Windows Vista'}
'error_info'
{'Id': 0, 'name':'no error'}
'user_status'
{'Id': 1, 'name':'off'}
'volume_letter','volume_id','volume_cost','volume_date','volume_end_date'
{'Id': 'asd12edsdasd', 'letter':'C','cost':100,'startdate':'2019-09-09 16:45:46.007','enddate':'2022-09-09 16:45:46.007'}

我试过这个final_result = {**mvalue, **vvalue}通过按照 SO 答案之一获取这两列。但它将两列连接为一列。它做了类似的东西error = {'0':'no error', '1':'error', '2': 'under obeservation'}

不能显示太多代码,但出于试用目的,可以像

import pandas as pd
d = {'id': [1, 2,3], 'system_name': ['abc','qrs','mln'], 'operating_system_id': [0,0,1], 'operating_system_name': ['Windows Vista', 'Windows Vista', Win&7'], 'error_info_id': [0,1,1], 'error_info_description':['no error', 'error', 'error'],'volume_letter': ['C','C','C'],'volume_id': ['12edsdasd', 'asd12edsd', 'asd12edasd'],'volume_cost':[100,100,100],'volume_date':['2019-09-09 16:45:46.007', '2019-09-09 16:45:46.007', '2019-09-09 16:45:46.007'],'volume_end_date':['2022-09-09 16:45:46.007','2022-09-09 16:45:46.007','2022-09-09 16:45:46.007']}
df = pd.DataFrame(data=d)

这些可以像每行字典一样合并成一个吗?

我不确定我是否理解这个问题,但如果您想将每一行转换为字典,您可以使用熊猫。DataFrame.to_dict("记录"(方法。

In[132]: df.to_dict('records') 
Out[132]: [{'id': 1, 'system_name': 'abc', 'operating_system_id': 0, 'operating_system_name': 'Windows Vista', 'error_info_id': 0, 'error_info_description': 'no error', 'volume_letter': 'C', 'volume_id': '12edsdasd', 'volume_cost': 100, 'volume_date': '2019-09-09 16:45:46.007', 'volume_end_date': '2022-09-09 16:45:46.007'},
{'id': 2, 'system_name': 'qrs', 'operating_system_id': 0, 'operating_system_name': 'Windows Vista', 'error_info_id': 1, 'error_info_description': 'error', 'volume_letter': 'C', 'volume_id': 'asd12edsd', 'volume_cost': 100, 'volume_date': '2019-09-09 16:45:46.007', 'volume_end_date': '2022-09-09 16:45:46.007'}, 
{'id': 3, 'system_name': 'mln', 'operating_system_id': 1, 'operating_system_name': 'Win&7', 'error_info_id': 1, 'error_info_description': 'error', 'volume_letter': 'C', 'volume_id': 'asd12edasd', 'volume_cost': 100, 'volume_date': '2019-09-09 16:45:46.007', 'volume_end_date': '2022-09-09 16:45:46.007'}]

必须浏览整个文档,但找到了初步解决方案

result['operating_system'] = result.apply(lambda row: {'id' : row.operating_system_id, 'name':row.operating_system_name}, axis=1)

现在每一行都有单独的行。

最新更新