《使用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数据库。这个方法不仅高效,而且易于操作,非常适合处理大规模数据。

相关推荐
这个DBA有点耶21 小时前
NULL不是空——数据库里最反直觉的设计,90%新人踩过的坑
数据库·mysql·代码规范
用户83562907805121 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805121 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
这个DBA有点耶1 天前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
镜舟科技1 天前
Databricks 再提 LTAP,AI 时代的数据底座为何重回大一统叙事?
数据库·架构·agent
Databend1 天前
从湖仓升级为 Agent 时代的数据控制面,Snowflake 和 Databricks 有哪些布局
大数据·数据库·agent
ClouGence1 天前
SQL Server CDC 能放到 Always On 备库读吗?一文讲透原理与实践
数据库·sql server
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python