pandas 的读写函数简表
读取函数 | 写入函数 | 解释 |
read_clipboard | to_clipboard | 从剪贴板中读取文本并传递给read_table |
read_csv | to_csv | 将CSV(逗号分隔)文件读入DataFrame |
read_excel | to_excel | Excel表格 |
read_sql | to_sql | |
read_pickle | to_pickle | |
read_json | to_json | |
read_msgpack | to_msgpack | |
read_stata | to_stata | |
read_gbq | to_gbq | 从Google BigQuery加载数据 |
read_hdf | to_hdf | |
read_html | to_html | |
read_parquet | to_parquet | |
read_feather | to_feather |
1、多年以来,人们已习惯于文本文件的读写,特别是列表形式的数据。如果文件每一行的多 个元素是用逗号隔开的,
则这种格式叫作CSV,这可能是最广为人知和最受欢迎的格式。
2、其他由空格或制表符分隔的列表数据通常存储在各种类型的文本文件中(扩展名一般 为.txt )。
3、因此这种文件类型是最常见的数据源,它易于转录和解释。pandas的下列函数专门用来处理 这种文件类型:read_csv、read_table、to_csv。
常用数据的读取
1 import pandas as pd
2
3 csvframe = pd.read_csv('pandas_data_test\myCSV_01.csv')
4 print(csvframe, "\n-----*-----")
5 csvframe1 = pd.read_table('pandas_data_test\myCSV_01.csv',sep=',')
6 print(csvframe1, "\n-----*-----")
7 csvframe2 = pd.read_csv('pandas_data_test\myCSV_02.csv',header=None) # 设置header为无,就不会用数据充当表头,此时添加默认表头
8 print(csvframe2, "\n-----*-----")
9 csvframe20 = pd.read_csv('pandas_data_test\myCSV_02.csv',names=['white','red','blue','green','animal']) # 指定表头
10 print(csvframe20, "\n-----*-----")
11
12 csvframe30 = pd.read_csv('pandas_data_test\myCSV_03.csv')
13 print(csvframe30, "\n-----*-----")
14 csvframe31 = pd.read_csv('pandas_data_test\myCSV_03.csv',index_col=['color','status']) #等级索引
15 print(csvframe31, "\n-----*-----")
16
17 txtframe4 = pd.read_table('pandas_data_test\ch05_04.txt',sep='\s+') # 根据正则解析
18 print(txtframe4, "\n-----*-----")
19 txtframe5 = pd.read_table('pandas_data_test\ch05_05.txt',sep=r'\D+',header=None,engine='python')
20 print(txtframe5, "\n-----*-----")
21 # 使用skiprows选项,可以排除多余的行。把要排除的行的行号放到数组中,赋给该选项即可。
22 txtframe6 = pd.read_table('pandas_data_test\ch05_06.txt',sep=',',skiprows=[0,1,3,6])
23 print(txtframe6)
24 Out[1]:
25 white red blue green animal
26 0 1 5 2 3 cat
27 1 2 7 8 5 dog
28 2 3 3 6 7 horse
29 3 2 2 8 3 duck
30 4 4 4 2 1 mouse
31 5 4 4 2 1 mou
32 -----*-----
33 white red blue green animal
34 0 1 5 2 3 cat
35 1 2 7 8 5 dog
36 2 3 3 6 7 horse
37 3 2 2 8 3 duck
38 4 4 4 2 1 mouse
39 5 4 4 2 1 mou
40 -----*-----
41 0 1 2 3 4
42 0 1 5 2 3 cat
43 1 2 7 8 5 dog
44 2 3 3 6 7 horse
45 3 2 2 8 3 duck
46 4 4 4 2 1 mouse
47 -----*-----
48 white red blue green animal
49 0 1 5 2 3 cat
50 1 2 7 8 5 dog
51 2 3 3 6 7 horse
52 3 2 2 8 3 duck
53 4 4 4 2 1 mouse
54 -----*-----
55 color status iteml item2 item3
56 0 black up 3 4 6
57 1 black down 2 6 7
58 2 white up 5 5 5
59 3 white down 3 3 2
60 4 white left 1 2 1
61 5 red up 2 2 2
62 6 red down 1 1 4
63 -----*-----
64 iteml item2 item3
65 color status
66 black up 3 4 6
67 down 2 6 7
68 white up 5 5 5
69 down 3 3 2
70 left 1 2 1
71 red up 2 2 2
72 down 1 1 4
73 -----*-----
74 white red blue green
75 0 1 5 2 3
76 1 2 7 8 5
77 2 3 3 6 7
78 -----*-----
79 0 1 2
80 0 0 123 122
81 1 1 124 321
82 2 2 125 333
83 -----*-----
84 white red blue green animal
85 0 1 5 2 3 cat
86 1 2 7 8 5 dog
87 2 3 3 6 7 horse
88 3 2 2 8 3 duck
89 4 4 4 2 1 mouse
从TXT文件读取部分数据
1 print(csvframe2, "\n-----*-----")
2 # nrows=2指定要获取的行数,skiprows=[2]删除对应行
3 csvfram20 = pd.read_csv('pandas_data_test\myCSV_02.csv',skiprows=[2],nrows=2,header=None)
4 print(csvfram20)
5 Out[2]:
6 0 1 2 3 4
7 0 1 5 2 3 cat
8 1 2 7 8 5 dog
9 2 3 3 6 7 horse
10 3 2 2 8 3 duck
11 4 4 4 2 1 mouse
12 -----*-----
13 0 1 2 3 4
14 0 1 5 2 3 cat
15 1 2 7 8 5 dog
另外一项既有趣又很常用的操作是切分想要解析的文本,然后遍历各个部分,逐一对其执行 某一特定操作。
例如,对于一列数字,每隔两行取一个累加起来,最后把和插人到Series对象中„这个小例 子理解起来很简单,
也没有实际应用价值,但是一旦领会了其原理,你就能将其用到更加复杂的情况。
1 csvframe1 = pd.read_table('pandas_data_test\myCSV_01.csv',sep=',')
2 print(csvframe1, "\n-----*-----")
3 out = pd.Series()
4 pieces = pd.read_csv('pandas_data_test\myCSV_01.csv',chunksize=4) # chunksize参数决定了每部分分割的行数
5 i = 0
6 for piece in pieces:
7 print(piece['white'])
8 out.at[i] = piece['white'].sum()
9 i += 1
10 print(out, "\n-----*-----")
11 Out[3]:
12 white red blue green animal
13 0 1 5 2 3 cat
14 1 2 7 8 5 dog
15 2 3 3 6 7 horse
16 3 2 2 8 3 duck
17 4 4 4 2 1 mouse
18 5 4 4 2 1 mou
19 -----*-----
20 0 1
21 1 2
22 2 3
23 3 2
24 Name: white, dtype: int64
25 4 4
26 5 4
27 Name: white, dtype: int64
28 0 8
29 1 8
30 dtype: int64
往CSV文件写入数据
1 print(csvframe1)
2 print(csvframe1.to_csv('pandas_data_test\ch05_07.csv'))
3 # 使用index和 header选项,把它们的值设置为False,可取消默认写入index和header
4 print(csvframe1.to_csv('pandas_data_test\ch05_07b.csv',index =False,header=False))
5 print(csvframe30.to_csv('pandas_data_test\ch05_08.csv'))
6 # 可以用to_csv()函数的na_rep选项把空字段替换为你需要的值。常用值有NULL、0和NaN
7 print(csvframe30.to_csv('pandas_data_test\ch05_09.csv',na_rep="空"))
8 Out[4]:
9 white red blue green animal
10 0 1 5 2 3 cat
11 1 2 7 8 5 dog
12 2 3 3 6 7 horse
13 3 2 2 8 3 duck
14 4 4 4 2 1 mouse
15 5 4 4 2 1 mou
16 None
17 None
18 None
19 None
进入文件夹我们可以看到相应的文件:
读写HTML文件
1 frame = pd.DataFrame(np.arange(4).reshape(2,2))
2 print(frame.to_html())
3 frame2 = pd.DataFrame( np.random.random((4,4)),index = ['white','black','red','blue1'],columns = ['up','down','right','left'])
4 s = ['<HTML>']
5 s.append('<HEAD><TITLE>My DataFrame</TITLE></HEAD>')
6 s.append(' <B0DY>')
7 s.append(frame.to_html())
8 s.append('</BODY></HTML>')
9 html = ''.join(s)
10 html_file = open('pandas_data_test\myFrame.html','w')
11 html_file.write(html)
12 html_file.close()
13 web_frames = pd.read_html('pandas_data_test\myFrame.html')
14 print(web_frames[0])
15 ranking = pd.read_html('http://www.meccanismocomplesso.org/en/ eccanismo-complesso-sito-2/classifica-punteggio/')
16 print(ranking[0][1:10]) # 输出网页内容的前10行
17 Out[5]:
18 <table border="1" class="dataframe">
19 <thead>
20 <tr style="text-align: right;">
21 <th></th>
22 <th>0</th>
23 <th>1</th>
24 </tr>
25 </thead>
26 <tbody>
27 <tr>
28 <th>0</th>
29 <td>0</td>
30 <td>1</td>
31 </tr>
32 <tr>
33 <th>1</th>
34 <td>2</td>
35 <td>3</td>
36 </tr>
37 </tbody>
38 </table>
39 Unnamed: 0 0 1
40 0 0 0 1
41 1 1 2 3
42 # Nome Exp Livelli
43 1 2 admin 9029 NaN
44 2 3 BrunoOrsini 2124 NaN
45 3 4 Berserker 700 NaN
46 4 5 Dnocioni 543 NaN
47 5 6 albertosallusti 409 NaN
48 6 7 Jon 233 NaN
49 7 8 Mr.Y 180 NaN
50 8 9 michele sisinni 157 NaN
51 9 10 Selina 136 NaN
从XML读取数据
pandas的所有I/O API函数中,没有专门用来处理XML(可扩展标记语言)格式的。虽然没有, 但这种格式其实
很重要,因为很多结构化数据都是以XML格式存储的。pandas没有专门的处理函 数也没关系,因为Python
有很多读写XML格式数据的库(除了pandas)。其中一个库叫作lxml,它在大文件处理方面性能优异,因而从
众多同类库之中脱颖而出。这 一节将介绍如何用它处理XML文件,以及如何把它和pandas整合起来,以最
终从XML文件中获 取到所需数据并将其转换为DataFrame对象。
XML源文件如下图所示
1 from lxml import objectify
2
3 xml = objectify.parse('pandas_data_test\\books.xml')
4 root = xml.getroot() # 获取根节点
5 print(root.Book.Author)
6 mes1 = root.Book.getchildren()
7 print("root.Book.getchildren()获取的子标签内容:\n", mes1)
8 mes2 = root.Book[1].getchildren() # 取第二个Book标签
9 print([child.tag for child in mes2]) # 获取子标签
10 print([child.text for child in mes2]) # 获取的子标签内容
11 Out[6]:
12 272103_l_EnRoss, Mark
13 root.Book.getchildren()获取的子标签内容:
14 [' 272103_l_EnRoss, Mark', 'XML Cookbook', 'Computer', 23.56, '2014-22-0l']
15 ['Author', 'Title', 'Genre', 'Price', 'PublishDate']
16 [' 272l03_l_EnBracket, Barbara', 'XML for Dummies', 'Computer', '35.95', '20l4-l2-l6']
读写 Microsoft Excel文件
read_excel()、to_excel(),能够读取.xls和.xlsx两种类型的文件。
读写JSON数据
read_json()、to_json()
HDF5格式
至此,已学习了文本格式的读写。若要分析大量数据,最好使用二进制格式。Python有多 种二进制数据处理
工具。HDF5库在这个方面取得了一定的成功。HDF代表等级数据格式(hierarchical data format )。HDF5
库关注的是HDF5文件的读写,这种文件的数据结构由节点组成,能够存储大量数据集。该库全部用c语言
开发,提供了python/matlab和Java语言接口。它的迅速扩展得益于开发人 员的广泛使用,还得益于它的效
率,尤其是使用这种格式存储大量数据,其效率很高。比起其他处理起二进制数据更为简单的格式,HDF5
支持实时压缩,因而能够利用数据结构中的重复模式压缩文件。目前,Python提供两种操纵HDF5格式数据
的方法:PyTables和h5py。这两种方法有几点不同,选用哪一种很大程度上取决于具体需求。
h5py为HDF5的高级API提供接口。PyTables封装了很多HDF5细节,提供更加灵活的数据容器、索引表、搜索
功能和其他计算相关的介质。pandas还有一个叫作HDFStore、类似于diet的类,它用PyTables存储pandas
对象。使用HDF5格式之前,必须导人HDFStore类。
1 from pandas.io.pytables import HDFStore
2 # 注意这里需要tables这个包,没有请自行安装
3 frame = pd.DataFrame(np.arange(16).reshape(4,4),index=['white','black1','red','blue'],columns=['up','down','right','left'])
4 store = HDFStore('pandas_data_test\mydata.h5')
5 store['obj1'] = frame
6 frame1 = pd.DataFrame(np.random.rand(16).reshape(4,4),index=['white','black1','red','blue'],columns=['up','down','right','left'])
7 store['obj2'] = frame1
8 print(store['obj1'])
9 print(store['obj2'])
10 Out[7]:
11 up down right left
12 white 0 1 2 3
13 black1 4 5 6 7
14 red 8 9 10 11
15 blue 12 13 14 15
16 up down right left
17 white 0.251269 0.422823 0.619294 0.273534
18 black1 0.593960 0.353969 0.966026 0.104581
19 red 0.964577 0.625644 0.342923 0.638627
20 blue 0.246541 0.997952 0.414599 0.908750
21 Closing remaining open files:pandas_data_test\mydata.h5...done