pandas - 从 MongoDB 字典到 Dataframe 映射
问题描述
在我之前的问题中,我将 DF 转换为要上传到 MongoDB 的字典列表。
现在我正在做相反的工作。从 MongoDB 查询中,我可以下载包含以下信息的字典列表:
[
{Info1: 3,
City: BCN,
Country: Spain},
{Info2: 5.6,
City: BCN,
Country: Spain},
{Info1: 4,
City: Moscow,
Country: Russia},
{Info2: 7,
City: Moscow,
Country: Russia}
]
现在我想创建一个表如下:
City Country Info1 Info2
BCN Spain 3 5.6
Moscow Russia 4 7
我现在这样做的方式如下:
def generate_excel(ind_type):
# first add columns
columns = ["City", "Country"]
# then find all indictors filtered
indicators = []
for indicator in CUSTOMERS_COLLECTION.find().distinct("ID"):
indicators.append(indicator)
# then add the indicators in column
columns = columns + indicators
# First find all Ciudades
cities = CUSTOMERS_COLLECTION.find()
rows_list = []
for ciudad in cities.distinct("City"):
indicators = CUSTOMERS_COLLECTION.find({"City": ciudad})
dict_ind = {}
# then we create a dict of the indicators. It will be the row
for indicator in indicators:
dict_ind[indicator["ID"]] = indicator["Valor"]
dict_ind["Country"] = indicator["Country"]
dict_ind["City"] = indicator["City"]
df_ = pd.DataFrame(rows_list, columns=columns)
return df_
与我之前的问题一样,这可行,但似乎根本没有优化。MongoDB 或 DF 是否有任何功能可以正确映射字典?
谢谢!!
解决方案
我不是 100% 这对你有用,但在过去我已经能够简单地将 mongo 查询转换为数据帧。例如:
q1=db.collection.find(#add whatever filters you need)
df= pd.DataFrame(q1)
请告诉我这是否有效。
推荐阅读
- javascript - JavaScript 中的反向 for 循环
- datetime - 您如何才能真正使 DateTime.now() 保持最新?
- gulp - 从 gulp v3 迁移到 v4
- java - JPA 插入优化
- ruby-on-rails - 耙子任务没有在红宝石中调用工人工作
- python - 绘制干净的 JSON 股票价格数据
- c# - 如何使用表达式将方法调用附加到类似构建器的调用链?
- ruby - 当我尝试使用 React 下载时,Sinatra 使用 `send_file` 发送损坏的 .zip 文件
- javascript - 如何在android webview中顺利拖动和旋转图像
- angular - 无法在 AWS Cognito 用户池应用程序客户端的回调 URL 中使用哈希 (#)