《使用Python将Excel数据批量写入MongoDB数据库》

在数据分析及处理过程中,我们经常需要将数据写入数据库。而MongoDB作为一种NoSQL数据库,其具有强大的可扩展性、高性能以及支持复杂查询等特性,广泛用于大规模数据存储和分析。在这篇文章中,我们将使用Python编写一个将Excel数据批量写入MongoDB的脚本,以便更加高效地管理数据。

首先,我们需要先安装必要的依赖包,即pandas和pymongo。在安装完毕后,我们可以使用如下代码连接到MongoDB数据库:

python 复制代码
import pandas as pd
from pymongo import MongoClient, UpdateOne

# 连接到MongoDB数据库
client = MongoClient('mongodb://localhost:27017/')
db = client['pms']
collection = db['hospital']

在连接到数据库之后,我们需要读取Excel文件,并对数据进行初步的处理。在这里,我们使用pandas库来读取Excel数据,然后使用一些函数对数据进行清洗和转换:

python 复制代码
# 读取Excel文件
excel_file = 'D:/下载/各省数据 - 副本/20230407北京各事业部用户客户数据汇总.xls'
df = (
    pd.read_excel(excel_file, skiprows=4, sheet_name='101')
    .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等来对数据进行处理。处理完成后,我们将数据转换为列表形式,并使用一个字典来将数据按照医院进行分组:

python 复制代码
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函数,它能够高效地批量添加、修改和删除数据:

python 复制代码
# 批量添加或更新数据
operations = []
for data in hospitals.values():
    operations.append(
        UpdateOne({'hospital': data['hospital']}, {'$set': data}, upsert=True)
    )
result = collection.bulk_write(operations)
print(f'添加或更新数据完毕,共执行 {result.modified_count + result.upserted_count} 项操作。')

最后,我们可以通过运行这些代码来将Excel数据批量写入MongoDB数据库。这种方法极大地提高了数据管理的效率,使我们能够更好地处理数据,更好地进行数据分析。

综上所述,本篇文章介绍了一个简单的Python脚本,可将Excel数据批量写入MongoDB数据库。这个方法不仅高效,而且易于操作,非常适合处理大规模数据。

相关推荐
FreakStudio2 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
丶21362 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
vvvae12343 小时前
分布式数据库
数据库
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
雪域迷影3 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
一个闪现必杀技3 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )4 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
bug菌¹4 小时前
滚雪球学Oracle[4.2讲]:PL/SQL基础语法
数据库·oracle
逸巽散人4 小时前
SQL基础教程
数据库·sql·oracle
卷心菜小温4 小时前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug