Pandas数据读写操作

目录

1.读/写文本文件

1.1文本文件的读取

1.2文本文件的存储

2.读/写Excel文件

2.1Excel文件的读取

2.2Excel文件的存储

3.JSON数据的读取与存储

3.1pandas读取JSON数据

3.2 JSON数据的存储

4.读取数据库文件

4.1Pandas读取MySQL数据

4.2 读取SQL Server中的数据


1.读/写文本文件

1.1文本文件的读取

文本文件是一种由若干行字符构成的计算机文件,它是一种典型的顺序文件。csv文件是一种以逗号分隔的文件格式,因为其分隔符不一定是逗号,又被称为字符分隔文件,文件以纯文本形式储存表格数据。

在Pandas中使用read_table函数来读取文本文件:

df1=pd.read_table('filepath',sep='\t',header='infer',names=None,index_col=None)

在Pandas中使用read_csv函数来读取CSV文件:

df2=pd.read_csv('filepath',ser=',',header='infer,names=None,index_col=None)

1.2文本文件的存储

df3.to_csv("df3.txt",mode='w')
df2.to_csv("df2.csv",mode="a")

2.读/写Excel文件

2.1Excel文件的读取

Pandas中使用read_excel函数读取xls合xlsx两种Excel文件

df=  pd.read_excel("filename.xls","Sheet1")
df=  pd.read_excel("filename.xlsx","Sheet1")

2.2Excel文件的存储

Pandas中使用to_excel方法将文件存储为Excel文件

df.to_excel('df.xls',mode='w')
df.to_excel('df.xlsx',mode='w')

3.JSON数据的读取与存储

3.1pandas读取JSON数据

使用read_json函数读取JSON数据,由于读取时会出现顺序错乱的问题,因此要对索引进行排序。

import pandas as pd
df=pd.read_json('filename')
df=df.sort_index#排序

3.2 JSON数据的存储

使用pd.to_json实现将数据存储为JSON文件。

df.to_json('df.json')

4.读取数据库文件

4.1Pandas读取MySQL数据

首先安装MySQLdb包,然后进行数据文件的读取。

import pandas as pd
import MySQLdb
conn=MySQLdb.connect(host=host,port=port,user=username,passwd=password,db=db_name)
df=pd.read_sql('select*from table_name',con=conn)
conn.close()

4.2 读取SQL Server中的数据

首先安装pymssql包,然后进行数据文件读取。

import pandas as pd
import pymssql
conn=pymssql.connect(host=host,port=port,user=username,passwd=password,database=database)
df=pd.read_sql('select*from table_name',con=conn)
conn.close()

猜你喜欢

转载自blog.csdn.net/m0_64087341/article/details/125417055