本文介绍: 在这篇文章中,我们将使用Python编写一个将Excel数据批量写入MongoDB的脚本,以便更加高效地管理数据。其中,我们使用了一些pandas的函数,如fillna、ffill、drop、assign等来对数据进行处理。在连接数据库之后,我们需要读取Excel文件,并对数据进行初步的处理。这种方法极大地提高了数据管理的效率,使我们能够更好地处理数据,更好地进行数据分析。综上所述,本篇文章介绍了一个简单的Python脚本,可将Excel数据批量写入MongoDB数据库

        在数据分析及处理过程中,我们经常需要将数据写入数据库。而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, 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等来对数据进行处理。处理完成后,我们将数据转换为列表形式,并使用一个字典来将数据按照医院进行分组

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}, upsert=True)
    )
result = collection.bulk_write(operations)
print(f'添加更新数据完毕,共执行 {result.modified_count + result.upserted_count} 项操作。')

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

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

原文地址:https://blog.csdn.net/qq1226546902/article/details/134599254

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_1641.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注