pandas读写数据操作
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、读写文本文件

1.to_csv函数写入文本文件

在这里插入代码片
import pandas as pd
a=pd.DataFrame([[1,4],[2,5],[3,6]],columns=['one_name',"two_name"],
index=[0,1,2])
print(a)
a.to_csv('aaa.csv')
写入之后就会出现文本文件!!!!如下图:  
2.read_csv函数读取文本文件

在这里插入代码片
import pandas as pd
a=pd.DataFrame([[1,4],[2,5],[3,6]],columns=['one_name',"two_name"],
index=[0,1,2])
print(pd.read_csv("itcast.csv",index_col=[0]))
显示结果:
one_name two_name
0 1 4
1 2 5
2 3 6
print(pd.read_table('itcast.csv'))
显示结果:
,one_name,two_name
0 0,1,4
1 1,2,5
2 2,3,6

二、读写excel文件
 
在这里插入代码片
b=pd.DataFrame({"col1":["爱国","敬业"],
"col2":["诚信","友善"]},
index=[0,1])
b.to_excel("itcast.xlsx")
写入成功就会显示表格数据  
在这里插入代码片
import pandas as pd
b=pd.DataFrame({"col1":["爱国","敬业"],
"col2":["诚信","友善"]},
index=[0,1])
print(pd.read_excel('itcast.xlsx')) 结果如下:
Unnamed: 0 col1 col2
0 0 爱国 诚信
1 1 敬业 友善
三、读取HTML表格数据
 
在这里插入代码片
import requests
import lxml
html_data = requests.get('http://kaoshi.edu.sina.com.cn/college/majorlist/')
html_data_content = pd.read_html(html_data.content,encoding='utf-8')
print(html_data_content[1])
爬取网页数据
在这里插入代码片
import pandas as pd
df=pd.DataFrame({"str":['a','b','d','e','f','k','d','s','l'],
'num':[1,2,4,5,3,2,6,2,3]},
index=[['A','A','A','C','C','C','B','B','B'],
[1,3,2,3,1,2,4,5,8]])
print(df.to_html())
效果显示:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th></th>
<th>str</th>
<th>num</th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="3" valign="top">A</th>
<th>1</th>
<td>a</td>
<td>1</td>
</tr>
<tr>
<th>3</th>
<td>b</td>
<td>2</td>
</tr>
<tr>
<th>2</th>
<td>d</td>
<td>4</td>
</tr>
<tr>
<th rowspan="3" valign="top">C</th>
<th>3</th>
<td>e</td>
<td>5</td>
</tr>
<tr>
<th>1</th>
<td>f</td>
<td>3</td>
</tr>
<tr>
<th>2</th>
<td>k</td>
<td>2</td>
</tr>
<tr>
<th rowspan="3" valign="top">B</th>
<th>4</th>
<td>d</td>
<td>6</td>
</tr>
<tr>
<th>5</th>
<td>s</td>
<td>2</td>
</tr>
<tr>
<th>8</th>
<td>l</td>
<td>3</td>
</tr>
</tbody>
</table>

双击html后缀名文件就可以显示文档!!!! 
读取数据库
 要导入模块
在这里插入代码片
from sqlalchemy import create_engine
   
|