pandas之IO数据读写

一前言

本篇文章读者如果学完,将会基本的pandas的IO操作API,为后面的数据分析打下坚实基础,基本通用的数据读写知识追寻者都已经给出示例,nosql这块请读者自行学习;如果文章觉得不错,随手点赞关注谢谢;读者的肯定就是对作者创作的最大支持;

二 CSV数据读写

2.1读取csv

zszxz_01.csv文件内容如下

number1,number2,number3,number4
1,2,3,4
5,6,7,8
9,10,11,12

使用read_csv() 函数可以读取csv文件

csv_frame = pd.read_csv("../file/zszxz_01.csv")
print(csv_frame)

输出

   number1  number2  number3  number4
0        1        2        3        4
1        5        6        7        8
2        9       10       11       12

2.2 指定表头读取CSV

zszxz_02.csv文件内容如下

1,2,3,4
5,6,7,8
9,10,11,12

使用names参数指定表头读取CSV

csv_frame = pd.read_csv("../file/zszxz_02.csv",names=['number1','number2','number3','number4'])
print(csv_frame)

输出

   number1  number2  number3  number4
0        1        2        3        4
1        5        6        7        8
2        9       10       11       12

2.3 将列指定为索引读取CSV

zszxz_03.csv文件内容如下

user1,number1,number2,number3
u1,2,3,4
u5,6,7,8
u9,10,11,12

使用参数index_col将列user1指定为索引读取CSV

csv_frame = pd.read_csv("../file/zszxz_03.csv",index_col=['user1'])
print(csv_frame)

输出

       number1  number2  number3
user1                           
u1           2        3        4
u5           6        7        8
u9          10       11       12

2.4读取指定区间段

zszxz_02.csv

1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16

读取指定区间段,意指读取文件中选定的行数;其中skiprows 属性 表示 跳过几行,行数从1 开始;由于文件中没指定列,这边可以使用header 指定为None,表示读取时不设置表头;

csv_frame = pd.read_csv('../file/zszxz_02.csv',skiprows=1, nrows= 2, header=None)
print(csv_frame)

输出

   0   1   2   3
0  5   6   7   8
1  9  10  11  12

2.5 逐块读取

zszxz_01.csv

number1,number2,number3,number4
1,2,3,4
5,6,7,8
9,10,11,12

逐块读取的含义类似矩阵中的分块矩阵,可以将矩阵切分为多个矩阵;分块后的数据集就是独立的部分;可以使用chunksize 属性指定分为几块;如下所示 chunksize = 2 表示分为两块,前面2 行一块,后面一行为1块;如果chunksize = 3 ; 就是每行一块;

csv_frame = csv_frame = pd.read_csv('../file/zszxz_01.csv', chunksize=2)
i = 0
for piece in csv_frame:
    print(piece)

输出

   number1  number2  number3  number4
0        1        2        3        4
1        5        6        7        8
   number1  number2  number3  number4
2        9       10       11       12

2.6写入 csv文件

写入csv文件使用to_csv() 函数,当然也可以使用 sep 参数指定分割符号;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

""" 写入 csv"""
index = ['user1','user2','user3']
data = np.arange(9).reshape(3,3)
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
frame.to_csv('../file/zszxz_w_01.csv')

文件内容

,zszxz,craler,rose
user1,0,1,2
user2,3,4,5
user3,6,7,8

三 读写txt

读取二进制文件中,常见的就是txt文本,txt文件的读取非常简单;

3.1 读取txt

zszxz_04.txt

user1 number1 number2 number3
u1 2 3 4
u5 6 7 8
u9 10 11 12

使用read_table()函数可以读取txt文件,其中分割符 \s 是表示空白符号,一般是使用指定符号,\s 是正则符号,更多的正则内容可以参照知识追寻者的正则文章进行学习;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

csv_frame = pd.read_table("../file/zszxz_04.txt",sep='\s',engine='python')
print(csv_frame)

输出

  user1  number1  number2  number3
0    u1        2        3        4
1    u5        6        7        8
2    u9       10       11       12

3.2 跳行读取

skiprows 表示跳行,跳的是给定的行数,数字从0开始表示第一行;与 skiprows 不同,其是跳了几行;

skiprows=[0,1] 与 skiprows=2 相同

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

csv_frame = pd.read_table("../file/zszxz_04.txt",sep='\s',engine='python',skiprows=[0,1])
print(csv_frame)

输出

   u5   6   7   8
0  u9  10  11  12

3.3写入 txt文件并指定分割符号

写入文件使用 to_table() 函数,不过知识追寻者使用to_csv 也成功了;

index = ['user1','user2','user3']
data = np.arange(9).reshape(3,3)
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
frame.to_csv('../file/zszxz_w_02.txt', index=False, header=False, sep='*')

文件内容

0*1*2
3*4*5
6*7*8

3.4写入 txt文件并替换空白字符

本来NaN 的元素输入到文件后会是空白字符,换句话说就不是NaN,如果要使用文件中的空白字符为NaN,则需要指定属性 na_rep='NaN'

index = ['user1','user2','user3']
data = [[1,],
        [1,2],
        [1,2,3]]
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
# NaN写入文件为空白字符,使用na_rep属性可以替换
frame.to_csv('../file/zszxz_w_03.txt', na_rep='NaN')

文件内容

,zszxz,craler,rose
user1,1,NaN,NaN
user2,1,2.0,NaN
user3,1,2.0,3.0

四 html读写

4.1读取网页数据

读取html可以直接通过 read_html()函数,读取时是读取table标签内容的数据;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

html = pd.read_html('https://fanyi.baidu.com/?aldtype=16047#auto/zh')
print(html)

输出

[        0         1
0    划词翻译       NaN
1    实时翻译       NaN
2    历史记录       NaN
3     NaN       NaN
4    发音语速    较慢中速较快
5  英语发音偏好      美式英式
6    发音模式  点击发音自动发音]

4.2 编写html文档

编写html网页使用to_html()函数,不过缺点是写出得页面很丑;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

""" 将dataFrame 转为 html 
需要安装 html5lib	1.0.1	
"""

#frame = pd.DataFrame(np.arange(4).reshape((2,2)))
#print(frame.to_html())

index = ['number','price','product']
data = np.random.random((3,3))
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)

doc = ['<!DOCTYPE html>']
doc.append('<html>')
doc.append('<head>')
doc.append('<title>zszxz dataFrame</title>')
doc.append('</head>')
doc.append('<body>')
# 将dataFrame添加至HTML body中
doc.append(frame.to_html())
doc.append('</body>')
doc.append('</html>')
html = '\n'.join(doc)

with open('../file/zszxzFrame.html', 'w') as html_file:
    html_file.write(html)


输出

<!DOCTYPE html>
<html>
<head>
<title>zszxz dataFrame</title>
</head>
<body>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>zszxz</th>
      <th>craler</th>
      <th>rose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>number</th>
      <td>0.382342</td>
      <td>0.509186</td>
      <td>0.906723</td>
    </tr>
    <tr>
      <th>price</th>
      <td>0.380164</td>
      <td>0.653920</td>
      <td>0.499396</td>
    </tr>
    <tr>
      <th>product</th>
      <td>0.450792</td>
      <td>0.506224</td>
      <td>0.627545</td>
    </tr>
  </tbody>
</table>
</body>
</html>

浏览器打开数据

五 excel数据读写

5.1读取默认sheet

zszxz_05.xlsx

user1	user2	user3
zszxz01	zszxz02	zszxz03
zszxz04	zszxz05	zszxz06
zszxz07	zszxz08	zszxz09

读取excel文件可以使用read_excel()函数默认读取sheet表单

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

"""
需要xlxd依赖 openpyxl
"""

#默认获取第一sheet
ex = pd.read_excel('../file/zszxz_05.xlsx')
print(ex)

输出

     user1    user2    user3
0  zszxz01  zszxz02  zszxz03
1  zszxz04  zszxz05  zszxz06
2  zszxz07  zszxz08  zszxz09

5.2 读取指定的sheet

如果要指定读取某个工作表 则需要使用属性sheet_name

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

ex = pd.read_excel('../file/zszxz_05.xlsx',sheet_name='Sheet1')
print(ex)

输出

     user1    user2    user3
0  zszxz01  zszxz02  zszxz03
1  zszxz04  zszxz05  zszxz06
2  zszxz07  zszxz08  zszxz09

5.3 写入excel

写入 excel文件使用 to_excel() 函数

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

# 写入指定的sheet
index = ['user1','user2','user3']
data = np.arange(9).reshape(3,3)
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
frame.to_excel('../file/zszxz_06.xlsx',sheet_name='知识追寻者')

文件内容

	zszxz	craler	rose
user1	0	1	2
user2	3	4	5
user3	6	7	8

六 json数据读写

6.1 写入json数据

写入json文件 使用to_json() 函数

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

index = ['number','price','product']
data = np.random.random((3,3))
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
frame.to_json('../file/zszxz_w_04.json')

输出

{
	"zszxz": {
		"number": 0.5790025071,
		"price": 0.8834134206,
		"product": 0.6333321225
	},
	"craler": {
		"number": 0.5481312627,
		"price": 0.7548320093,
		"product": 0.6435874093
	},
	"rose": {
		"number": 0.6774161492,
		"price": 0.0685865804,
		"product": 0.7100822242
	}
}

6.2 读取json数据

读取json文件使用 read_json() 函数

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

json = pd.read_json('../file/zszxz_w_04.json')
print(json)

输出

            zszxz    craler      rose
number   0.223647  0.926946  0.159471
price    0.827019  0.385435  0.600110
product  0.438179  0.335952  0.068237

七 读写数据库

读写数据库,postgresql的示例如下,如果是其它数据库只需要改动引擎内容即可,比如mysql的引擎如下

engine = create_engine('mysql+pymysql://username:password@ip:port/database')

7.1 读取postgresql使用sql

通过sql的方式读取表

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from sqlalchemy import create_engine

# 需要 psycopg2 依赖
engine = create_engine('postgresql://postgres:123456@localhost:5432/python')
# 查询语句
sql_query = 'select * from student;'
# 执行sql
result = pd.read_sql_query(sql_query, engine)
print(result)

输出

   id  num   name
0   1  100  zszxz
1   2  101  zszxz
2   5  102  知识追寻者
3   6  102  知识追寻者

7.2 读取postgresql表

直接指定表名,读取整张表

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from sqlalchemy import create_engine
# 需要 psycopg2 依赖
engine = create_engine('postgresql://postgres:123456@localhost:5432/python')
# 执行sql
result = pd.read_sql_table('student', engine)
print(result)

输出

   id  num   name
0   1  100  zszxz
1   2  101  zszxz
2   5  102  知识追寻者
3   6  102  知识追寻者

7.3 写入数据至postgresql

注意这边写入的数据库表会自动新建一张表;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from sqlalchemy import create_engine
# 需要 psycopg2 依赖
engine = create_engine('postgresql://postgres:123456@localhost:5432/python')

index = ['number','price','product']
data = np.random.random((3,3))
columns = ['id','num','name']
frame = pd.DataFrame(data,index,columns)
frame.to_sql('new_student', engine)

八 HDF5文件读写

HDF5文件也就是等级数据库文件,处理分析大数据时会用到;

# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from pandas.io.pytables import  HDFStore

index = ['number','price','product']
data = np.random.random((3,3))
columns = ['zszxz','craler','rose']
frame = pd.DataFrame(data,index,columns)
# 创建HDF5 文件
hdf = HDFStore('../file/zszxz_w_05.h5')
# 将 frame 存储进 HDF5文件
hdf['object1'] = frame
# 读取
print(hdf['object1'])

输出

            zszxz    craler      rose
number   0.480612  0.473889  0.531245
price    0.213813  0.153765  0.875458
product  0.039371  0.989284  0.764272
发布了148 篇原创文章 · 获赞 375 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/youku1327/article/details/104662139
今日推荐