pandas文件读取与存储

一、CSV文件

1. 读取csv文件,获取数据

python 复制代码
pd.read_csv('路径', sep='分隔符', usecols=[ '列名1', '列名2', ...] )

2. 把读取到的数据写到文件中

python 复制代码
df.to_csv('路径.csv', sep=',', index=False ) # 默认为True,会带上索引保存

3. 特殊的csv文件-->tsv文件

区别:csv文件以 ',' 做分隔;tsv文件以 tab键 做分隔

pd.read_csv('路径.tsv', sep='\t', index_col=0) # 第0列设置为索引列

df.to_csv('路径.tsv', sep='\t', index=True ) # 默认为True,会带上索引保存

二、MySQL数据库

1.导包

python 复制代码
from sqlalchemy import create_engine

2.读取要写入sql数据库的数据

python 复制代码
data = pd.read_csv('路径', encoding='gbk', index_col=0)

3. 创建引擎对象

python 复制代码
engine = create_engine('数据库+模块名://数据库的用户名:密码@主机名:端口号/数据库名?编码方式')

4. 将数据写入sql数据库

参1:数据表名 参2:引擎对象 参3:是否把索引写进数据库 参4:数据表存在如何处理

append是在表后追加写 replace是覆盖原表

python 复制代码
data.to_sql('表名', engine, index=False, if exists='append')

5. 从sql中读取数据

参1:书就表名或sql语句 参2:引擎对象

python 复制代码
sql_df = pd.read_sql('表名', engine)

sql_df = pd.read_sql('select * from 表名', engine)  # 里面也可以写sql语句

三、json文件

1. 读取json文件

参1:文件路径 参2:读取形式:records、columns(默认格式)、index 参3:是否按行读取

python 复制代码
json_df = pd.read_json('文件路径', orient='读取形式', lines=True)

2. 把数据写入json文件中

json_df.to_json('文件路径', orinet='records') # 结果为:{}, {}, {},...

json_df.to_json('文件路径', orinet='records', lines=True) # 结果为:{}, {}, {},...常用

json_df.to_json('文件路径', orinet='index') # 结果为:index:{...}

json_df.to_json('文件路径', orinet='columns', lines=True) # 结果为:columns:{...}

相关推荐
花酒锄作田21 小时前
Pydantic校验配置文件
python
hboot21 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python