【问题标题】:Process the data in the database and write to a new table处理数据库中的数据并写入新表
【发布时间】:2020-03-24 15:17:35
【问题描述】:

我遇到的问题是处理数据库中的一个表,然后将所有表合并到另一个表中。

表结构是这样的:

拥有 3 个数据库表。

我想通过Entryid合并到表中

我的想法是用 pandas 和 process 提取数据。

但是写入数据库有很多问题。

下面是我试过的代码:

# -*- coding: UTF-8 -*-
import pandas as pd
import pymongo


def data_Process():
    client = pymongo.MongoClient(host="mongodb://localhost:27017/")

    collection1 = client.test.declare_customs
    collection2 = client.test.tax
    collection3 = client.test.ship
    collection4 = client.test.jieguan

    data1 = pd.DataFrame(list(collection1.find()))
    data2 = pd.DataFrame(list(collection2.find()))
    data3 = pd.DataFrame(list(collection3.find()))
    data3 = data3.groupby(by=['entryId']).agg(';'.join)

    data4 = pd.merge(data1, data2, on='entryId', how='left')
    data5 = pd.merge(data4, data3, on='entryId', how='left')

    data5.to_excel('data5.xlsx')
    collection4.insert(data5)



if __name__ == '__main__':
    data_Process()

错误:

如果你有更好的主意。

谢谢。

【问题讨论】:

  • 跟随该错误消息将您带到哪里?

标签: python pandas mongodb


【解决方案1】:

参考下面的答案,

Insert a Pandas Dataframe into mongodb using PyMongo

https://stackoverflow.com/a/20167984/3704501

在插入 mongo 集合之前,您需要将 pandas 数据帧转换为 json 格式

【讨论】:

  • 嗨,我知道原因` data3 = pd.DataFrame(list(collection3.find())) if True: del data3['_id'] `我需要从数据中删除ID由 mongodb 导出
  • @hakukou if True?顺便说一句,您不应该使用del 删除列,请使用drop()
  • @Alexander Cécile 嗨,是的,我需要删除“_id”
  • @hakukou if True 来自哪里?使用.drop() 删除该列。
  • @Alexander Cécile 如果不需要 True,是的,我使用了 .drop(columns='_id') 非常感谢
猜你喜欢
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 2017-07-16
相关资源
最近更新 更多