是否可以通过匹配 id 从数据框中更新 MongoDB 集合中的多条记录?数据框 _id text sentiment0 5ec299fa905e038dec3c8e93 Kederi Yusof· basikal salah Najib.Tayar pa... 11 5ec49452bfcd4786382fe21f Serindik.com·2 laaa mimpi UMNO.... XPM7 pul... 02 5ec40e8d28fb32986041df16 Newpaper24·4m1MDB: Najib Razak’s court, accuse... -13 5ec44c0b255995f0522fe1ec falseprophet· low pesuruh najib. Budak des... 14 5ed2ab347d23a5d56d59a730 Kamaluddin 阿列克斯 தீன்·11m-anak-najib-dalam-sena... 0代码updates = []for document in db.twitter.find(): for index, row in document.iterrows(): if(row['_id']==a['_id']): updates.append(UpdateOne({'_id': row['_id']}, {'$set': {'sentiment': row['sentiment']}}, upsert=True)) breakdb.twitter.bulk_write(updates)但我收到AttributeError: 'dict' object has no attribute 'iterrows'错误信息
1 回答
回首忆惘然
TA贡献1847条经验 获得超11个赞
您不需要查找循环,只需使用它iterrows()来获取数据并UpdateOne执行更新插入。
from pymongo import MongoClient, UpdateOne
import pandas as pd
db = MongoClient()['mydatabase']
data = [['ec299fa905e038dec3c8e93', 'Kederi Yusof· basikal salah Najib.Tayar pa...', 1],
['ec49452bfcd4786382fe21f', 'Serindik.com·2 laaa mimpi UMNO.... XPM7 pul...', 0]]
df = pd.DataFrame(data, columns=['_id', 'text', 'sentiment'])
updates = []
for _, row in df.iterrows():
updates.append(UpdateOne({'_id': row.get('_id')}, {'$set': {'sentiment': row.get('sentiment')}}, upsert=True))
db.twitter.bulk_write(updates)
添加回答
举报
0/150
提交
取消