我正在嘗試在 Pandas 中讀取 CSV 檔案,將每一行轉換為 JSON 物件并將它們附加到 dict 中,然后存盤在 MongoDB 中。
這是我的代碼
data = pd.DataFrame(pd.read_csv('data/airports_test.csv'))
for i in data.index:
json = data.apply(lambda x: x.to_json(), axis=1)
json_dict = json.to_dict()
print(json_dict[5])
ins = collection.insert_many(json_dict)
# for i in json_dict:
# ins = collection.insert_one(json_dict[i])
如果我列印 dict 的元素,我會得到正確的輸出(我認為..)。如果我嘗試使用 collection.insert_many,我會收到錯誤'documents must be a non empty list'如果我嘗試遍歷字典并一次添加一個,我會收到錯誤
document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
我已經用谷歌搜索了,但我似乎找不到解決方案!任何幫助將不勝感激。
uj5u.com熱心網友回復:
您可以通過以下方式跳過處理 DataFrame 的各個行:
import json
import pandas
data = pandas.DataFrame(pandas.read_csv('test2.csv'))
data = data.to_dict(orient="records")
collection.insert_many(data)
順便說一句,我認為我會親自使用該csv模塊,dictReader而不是pandas在這里,但這種方式很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446255.html
