[英]Import specific data from mongo to pandas dataframe
我在 mongodb 中的一個集合中有大量數據需要分析,使用 pandas 和 jupyter 中的 pymongo。 我正在嘗試導入 dataframe 中的特定數據。
樣本數據。
{
"stored": "2022-04-xx",
...
...
"completedQueues": [
"STATEMENT_FORWARDING_QUEUE",
"STATEMENT_PERSON_QUEUE",
"STATEMENT_QUERYBUILDERCACHE_QUEUE"
],
"activities": [
"https://example.com
],
"hash": "xxx",
"agents": [
"mailto:example@example.com"
],
"statement": { <=== I want to import the data from "statement"
"authority": {
"objectType": "Agent",
"name": "xxx",
"mbox": "mailto:example@example.com"
},
"stored": "2022-04-xxx",
"context": {
"platform": "Unknown",
"extensions": {
"http://example.com",
"xxx.com": {
"user_agent": "xxx"
},
"http://example.com": ""
}
},
"actor": {
"objectType": "xxx",
"name": "xxx",
"mbox": "mailto:example@example.com"
},
"timestamp": "2022-04-xxx",
"version": "1.0.0",
"id": "xxx",
"verb": {
"id": "http://example.com",
"display": {
"en-US": "viewed"
}
},
"object": {
"objectType": "xxx",
"id": "https://example.com",
"definition": {
"type": "http://example.com",
"name": {
"en-US": ""
},
"description": {
"en-US": "Viewed"
}
}
}
}, <=== up to here
"hasGeneratedId": true,
...
...
}
請注意,我只對嵌套在“語句”下的數據感興趣,而不對包含字符串的任何數據感興趣,即它上面的“STATEMENT_FORWARDING_QUEUE”。
我想要完成的是從 dataframe 中的“聲明”(如上所示)導入數據,並以如下方式排列它們:
ID | 權限對象類型 | 權威名稱 | 權限 mbox | 存儲 | 語境平台 | 上下文擴展 | 演員對象類型 | 演員姓名 | ... |
---|---|---|---|---|---|---|---|---|---|
00 | 代理人 | xxx | 郵箱 | 2022- | 未知 | http://1 | xxx | xxx | ... |
01 | 代理人 | yyy | 郵箱 | 2022- | 未知 | http://2 | yyy | yyy | ... |
這個想法是能夠訪問任何數據,如“權限名稱”或“參與者對象類型”。
我努力了:
df = pd.DataFrame(list(collection.find(query)(filters)))
df = json_normalize(list(collection.find(query)(filters)))
使用各種查詢、過濾器和切片,以及聚合和映射/減少,但沒有產生正確的 output。
我還想根據“存儲”字段(sort('$natural',-1)?)進行排序(從最新到最舊),並且也可能將 limit(xx) 應用於 dataframe。
有任何想法嗎?
提前致謝。
嘗試這個
df = json_normalize(list(
collection.aggregate([
{
"$match": query
},
{
"$replaceRoot": {
"newRoot": "$statement"
}
}
])
)
感謝您的回答,@pavel。 它是正確的,幾乎可以解決問題。
我還添加了排序和限制,所以如果有人感興趣,最終代碼如下所示:
df = json_normalize(list(
statements_coll.aggregate([
{
"$match": query
},
{
"$replaceRoot": {
"newRoot": "$statement"
}
},
{
"$sort": {
"stored": -1
}
},
{
"$limit": 10
}
])
))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.