python数据保存:记录pandas数据分析完成后的轻量级数据保存!

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

本文说的轻量级的数据保存指的是sqlite比如一些手机App的操作都会采用该数据库来完成对数据保存。

一个sqlite数据库的大小在KB之间pandas模块提供的DataFrame数据对象也支持了关于sqlite的引擎。

为了减少数据保存的磁盘空间使得excel或者csv等格式的数据分析结果进行统一化的保存使用sqlite的极好的。

这里使用两个python的非标准库分别是pandas和sqlalchemy若是没有则使用pip的方式直接安装即可。

pip install pandas

pip install sqlalchemy

使用方式也比较简单将这两个安装好的模块分别导入到代码块中。

# Importing the pandas module and giving it an alias of pd.
import pandas as pd

# Importing the create_engine function from the sqlalchemy module.
from sqlalchemy import create_engine

将本地的excel或者csv数据读取返回DataFrame对象现实情况中可能还要进行数据处理。

# Reading the excel file and storing it in a dataframe.
data_frame = pd.read_excel('D:/test-data-work/data.xlsx')

# Printing the dataframe.
print(data_frame)

这个时候DataFrame格式的数据已经存在了现在考虑使用sqlite将数据进行保存。

首先使用sqlalchemy模块的create_engine函数创建sqlite的数据库引擎。

# Creating a sqlite database called test.db.
engine = create_engine('sqlite:///test.db')

使用DataFrame对象提供的to_sql()函数将该data_frame保存到sqlite数据库表名称为data的数据表中。

# Saving the dataframe to the sqlite database.
data_frame.to_sql('data', engine)

保存完成之后会在本地的当前环境下生成test.db的数据库文件了。

若是想要读取存储的结果pandas模块也提供了read_sql()函数读取后再次返回DataFrame的数据对象。

# Reading the data from the sqlite database.
result_ = pd.read_sql('data', engine)

# Printing the dataframe that was read from the sqlite database.
print(result_)

#      index          姓名   年龄    班级   成绩 表现       入学时间
# 0        0  Python 集中营   10  1210   99  A 2022-10-17
# 1        1  Python 集中营   11  1211  100  A 2022-10-18
# 2        2  Python 集中营   12  1212  101  A 2022-10-19
# 3        3  Python 集中营   13  1213  102  A 2022-10-20
# 4        4  Python 集中营   14  1214  103  A 2022-10-21
# ..     ...         ...  ...   ...  ... ..        ...
# 194    194  Python 集中营  186  1386  275  A 2023-04-29
# 195    195  Python 集中营  187  1387  276  A 2023-04-30
# 196    196  Python 集中营  188  1388  277  A 2023-05-01
# 197    197  Python 集中营  189  1389  278  A 2023-05-02
# 198    198  Python 集中营  190  1390  279  A 2023-05-03

如果有直接操作sqlite数据库的需要可以到sqlite官网下载客户端工具直接进行SQL层面的增删改查操作。

https://www.sqlite.org/download.html

往期精彩

知识记录python如何通过反射机制处理对象

如何使用Selenium IDE浏览器插件轻松完成脚本录制轻松搞定自动化测试

python数据可视化数据分析后的词云图片生成

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python