numpy 如何从SqlAlchemy输出中生成嵌套字典(Python)?

h5qlskok  于 2023-03-02  发布在  Python
关注(0)|答案(1)|浏览(184)

下面是SqlAlchemyselect操作符的输出。

| device_id |     event_name      | event_count |
| :--------:| :-----------------: |:-----------:|
| 123456    | speed more than 100 |      3      |
| 123456    | speed less than 12  |      0      |
| 334455    | out of NYC          |      5      |
| 111111    | in UCSD campus      |      1      |

现在,我想将这个结果保存到一个嵌套字典中,格式如下,但我不知道如何高效地完成。
我需要一个字典,其中键是device_id,值是字典,其中键是event_name,值是event_count

{'123456' : {'speed more than 100' : 3,
             'speed less than 12': 0},
 '334455' : {'out of NYC' : 5},
 '111111' : {'in UCSD campus' : 1}
}

这是我的代码。

def count_per_event_json(self, count_per_event_query_result):
        result = {}
        print(count_per_event_query_result)
        for item in enumerate(count_per_event_query_result):
            if item[0] not in result.keys():
                # result[item[0]] = {I don't know how to fill this inner dict'}
    
        return result

我还计算了输入参数并将其传递给函数,如下所示:

def count_per_event(self):
    count_per_event_query = select(EventsModel.device_id, EventsModel.event_name,
                                   func.count(EventsModel.rule_table_id)) \
        .where(EventsModel.timestamp <= self.max_utc_timestamp) \
        .where(EventsModel.timestamp >= self.min_utc_timestamp) \
        .group_by(EventsModel.device_id, EventsModel.rule_table_id) \
        .execution_options(synchronize_session="fetch")

    return count_per_event_query

async def cube_calculator(self):
     async with async_session() as session:
                count_per_event_query_result = await session.execute(self.count_per_event())
                json = self.count_per_event_json(count_per_event_query_result) # the type of  count_per_event_query is  <class 'sqlalchemy.engine.result.ChunkedIteratorResult'>
krcsximq

krcsximq1#

您可以使用pandas执行此操作:

import pandas as pd

# Use pandas.read_sql to read the query results into a dataframe
df = pd.read_sql(select_query, con=your_db_connection)

# Use the pandas groupby function to group the dataframe by device_id
grouped_df = df.groupby('device_id')

# Convert the grouped dataframe into a nested dictionary using the to_dict method
result_dict = grouped_df.apply(lambda x: x.set_index('event_name')['event_count'].to_dict()).to_dict()

相关问题