数据导入和导出
(一)读取csv文件
使用函数:read_cdv(),具体详见:/pandas-docs/stable/generated/pandas.read_csv.html
1.本地读取,实例1:
>>> import pandas as pd>>> df=pd.read_csv('F:\\python_test\\binary.csv')>>> df<class 'pandas.core.frame.DataFrame'>Int64Index: 400 entries, 0 to 399Data columns (total 4 columns):admit 400 non-null valuesgre400 non-null valuesgpa400 non-null valuesrank400 non-null valuesdtypes: float64(1), int64(3)
实例2:
import csvcsvfile = file('F:\\python_test\\csv_test.csv', 'rb')reader = csv.reader(csvfile)for line in reader:print linecsvfile.close()
2.网络读取
import pandas as pddata_url = "https://****.csv" #填写url读取df = pd.read_csv(data_url)
3.数据写入
语法:csv.writer(fileobj [, dialect='excel'][optional keyword args])
示例:
import csvcsvfile = file('F:\\python_test\\csv_test.csv', 'wb')writer = csv.writer(csvfile)writer.writerow(['姓名', '年龄', '电话'])data = [('小河', '25', '12345'),('小芳', '19', '78945')]writer.writerows(data)csvfile.close()
(二)读取mysql数据
Mysql基本教程:/mysql/mysql-tutorial.html
假设数据库安装在本地,用户名为username,密码为password,要读取mydb数据库中的数据
import pandas as pdimport MySQLdbmysql= MySQLdb.connect(host='localhost', port=3306,user='username', passwd='password', db='mydb')df = pd.read_sql('select * from test;', con=mysql) mysql.close()
(三)读取excel
首先要安装xlrd模块:/article/17bd8e5227bb8b85ab2bb8b2.html
1导入模块
import xlrd
2 打开excel文件
data = xlrd.open_workbook('1.xlsx')
3 获取一个工作表方法
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取
4 获取整行或整列的值,-->返回数组
table.row_values(i)
table.col_values(i)
5 获取行数和列数
nrows = table.nrows
ncols = table.ncols
6 循环表获取行数据,--->返回数据
for i in range(nrows ):
print table.row_values(i)
7 单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
也可以使用行列号进行索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
参考:/lhj588/archive//01/06/2314181.html