将postgresql数组\u agg查询转换为Dataframe代码

kgqe7b3p  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(411)

这是postgresql查询,我希望它使用pandasDataframe来编写它。

SELECT
    A.id,
    ARRAY_AGG(STRUCT(
        B.b_id,
        C.c_id,
        C.code,
        c.desc
    )) AS conditions
FROM A JOIN B ON A.id = B.id 
JOIN C ON B.b_id = C.c_id

当使用 df.to_json(r'output.json', orient='records') ```
[
"id": 123
"conditions": [
{
"b_id": 23,
"c_id": 23,
"code": "some secret",
"desc": "blah blah"
},
{
"b_id": 24,
"c_id": 24,
"code": "secret code",
"desc": "this is description"
}
]
]

到目前为止这是我的代码

import pandas as pd

Adf = pd.DataFrame({'id': [123]})
Bdf = pd.DataFrame({'id': [123, 123], 'b_id': [23, 24]})
Cdf = pd.DataFrame({'c_id': [23, 24], 'code': ['some secret', 'secret code'], 'desc': ['blah blah', 'this is description']})

df = Adf.merge(Bdf, left_on='id', right_on='id', how='inner')

df = df.merge(Cdf, left_on='b_id', right_on='c_id', how='inner')

print(df)

输出-

id b_id c_id code desc
0 123 23 23 some secret blah blah
1 123 24 24 secret code this is description

我不知道如何执行数组\u agg。
2sbarzqh

2sbarzqh1#

如果要在Dataframe结构中使用它,就必须分解 ARRAY_AGG 因为Dataframe不支持这种结构。

SELECT
    A.id,
    B.b_id,
    C.c_id,
    C.code,
    C.desc
FROM A JOIN B ON A.id = B.id 
JOIN C ON B.b_id = C.c_id

然后你可以执行pandas命令。

相关问题