网站建设路由设置,微擎微信管理系统,网站推广教程优化整站,科技网站建设分析在数据分析及处理过程中#xff0c;我们经常需要将数据写入数据库。而MongoDB作为一种NoSQL数据库#xff0c;其具有强大的可扩展性、高性能以及支持复杂查询等特性#xff0c;广泛用于大规模数据存储和分析。在这篇文章中#xff0c;我们将使用Python编写一个将Excel数据批… 在数据分析及处理过程中我们经常需要将数据写入数据库。而MongoDB作为一种NoSQL数据库其具有强大的可扩展性、高性能以及支持复杂查询等特性广泛用于大规模数据存储和分析。在这篇文章中我们将使用Python编写一个将Excel数据批量写入MongoDB的脚本以便更加高效地管理数据。 首先我们需要先安装必要的依赖包即pandas和pymongo。在安装完毕后我们可以使用如下代码连接到MongoDB数据库
import pandas as pd
from pymongo import MongoClient, UpdateOne# 连接到MongoDB数据库
client MongoClient(mongodb://localhost:27017/)
db client[pms]
collection db[hospital]在连接到数据库之后我们需要读取Excel文件并对数据进行初步的处理。在这里我们使用pandas库来读取Excel数据然后使用一些函数对数据进行清洗和转换 # 读取Excel文件
excel_file D:/下载/各省数据 - 副本/20230407北京各事业部用户客户数据汇总.xls
df (pd.read_excel(excel_file, skiprows4, sheet_name101).iloc[0:-3] # 删除倒数3行.iloc[:, 2:] # 删除前俩列.drop(columns[备注]) # 删除最后1列.fillna({护士: 0}) # 用指定的值填充缺失值.ffill() # 填充空值.assign( # 拆分序列医院名称lambda x: x[医院名称].str.split(\n),科室lambda x: x[科室].ffill().apply(int), # 转换类型床位lambda x: x[床位].ffill().apply(int), # 转换类型)
)其中我们使用了一些pandas的函数如fillna、ffill、drop、assign等来对数据进行处理。处理完成后我们将数据转换为列表形式并使用一个字典来将数据按照医院进行分组
data_list df.values.tolist()
hospitals {}
for result in data_list:hospital_name result[0][0]if hospital_name not in hospitals:hospitals[hospital_name] {hospital: result[0][0],department: result[1],bed: result[2],doctor: [result[3]],nurse: [result[4]],}else:if result[3] not in hospitals[hospital_name][doctor]:hospitals[hospital_name][doctor].append(result[3])if result[4] ! 0 and result[4] not in hospitals[hospital_name][nurse]:hospitals[hospital_name][nurse].append(result[4])在生成字典之后我们需要将数据批量写入MongoDB数据库中。这里使用了pymongo库的bulk_write函数它能够高效地批量添加、修改和删除数据
# 批量添加或更新数据
operations []
for data in hospitals.values():operations.append(UpdateOne({hospital: data[hospital]}, {$set: data}, upsertTrue))
result collection.bulk_write(operations)
print(f添加或更新数据完毕共执行 {result.modified_count result.upserted_count} 项操作。)最后我们可以通过运行这些代码来将Excel数据批量写入MongoDB数据库。这种方法极大地提高了数据管理的效率使我们能够更好地处理数据更好地进行数据分析。 综上所述本篇文章介绍了一个简单的Python脚本可将Excel数据批量写入MongoDB数据库。这个方法不仅高效而且易于操作非常适合处理大规模数据。