【发布时间】:2015-04-21 18:09:25
【问题描述】:
我目前正在使用 Python 3.4.2 中的 Pandas (0.14.1) 使用 pymongo (2.8) 从 Mongo 数据库导入数据。通过简单的导入,
cur = db.collection.find()
df = pd.DataFrame(list(cur))
我收到以下错误:
InvalidBSON: 'utf-8' codec can't decode byte 0xed in position 3123: invalid continuation byte
导入注意:以前,我在 Python 2.7+ 中使用 pandas 执行相同的任务(将相同的集合导入到 pandas 数据帧中进行处理),并且所有导入都没有问题。由于其他原因,我现在更愿意留在 3.4+ 环境中。
虽然我无法共享数据,但我可以说它是 UTF-8 编码的(这会使错误令人困惑)我批量导入 MongoDB 的行分隔 JSON 文档。一些字段包含许多 unicode 字符。到目前为止,在 mongo 控制台和 python 2.7+ 中使用只读(来自 db)任务,我还没有遇到上述问题。作为检查,在 python 3.4 中出现此错误后,我在 2.7 中运行了相同的代码(对于相同的 db 集合)并且导入正常。
是否有人能够提供一些关于正在发生的事情的见解,或者提供一些支持来解决问题?我愿意提供我所能提供的任何其他信息。
更新:
我使用
识别了有问题的文档for doc in cur.sort([('_id', 1)]): print(doc['_id'])
并取最后一个列出的_id。但是,有一些奇怪的行为。具体来说,如果我使用
创建一个 DataFramepd.DataFrame(list(db.collection.find({'_id' : ObjectId('offending _id')}))
它工作正常。同一个文档存在于多个集合中,并在尝试导入完整集合时在每个集合中抛出错误。
文档:
{"app_name" : "Tiles", "description" : "Tiles is a sliding tile puzzle, also known as a \"15 Puzzle\". Using Tiles, you choose photos from your Photo Library on your iPhone or iPod Touch, or use the built-in camera on your iPhone. Tiles then cuts the photo into tiles and scrambles them into a fun puzzle for you to solve! Your job is to slide the tiles around and re-assemble the photo!\n\nSee if you can re-assemble the photo in the least number of moves or the fastest time possible! Challenge your friends to beat your time! Choose from an infinite number of images you create yourself, and up to 4 different puzzle configurations.\n\nFeatures:\n\n* 9, 16, 25, or 36 Tile Selections\n* Integrated with the built in iPhone camera and Photo Library so you can use your photos for puzzles.\n\nBy Request: A standard \"15\" Puzzle image can be downloaded at http://www.random-ideas.net/Software/Tiles/16.png simply download it and sync it with your phone (via iTunes) touse it.\n\nIn keeping with our company mission, we will be donating 5% of the pre-tax net profits from Tiles to charity. The selected charity for Tiles will be to benefit autism.\n \n \n", "whats_new" : "Fixed a rare crashing bug while selecting a new image.\n \n \n"}
【问题讨论】:
-
您能否准确追踪哪个文档出现此错误并将其发布到问题中?
-
这个问题已经更新了一些额外的信息。
-
我想你可能正在点击PYTHON-721。您可以在 mongo shell 中加载文档吗?此外,您可能得到了最后一个工作文档而不是第一个非工作文档 - 您可以尝试在
_id上排序,在 python 中找到最后一个工作文档,然后使用 mongo shell 以相同的顺序查找下一个文档. -
啊,听起来很相似。是的,我可以在 mongo shell 中打开受影响的文档。奇怪的是它在 Python 2.7+ 中运行良好,但在 3.4 中引发了错误。
-
我认为这意味着你必须清理你的数据,摆脱糟糕的 utf-8。
标签: python mongodb python-3.x pandas pymongo